Instant Hands-on Testing with PHPUnit How-to A practical guide to getting started with PHPUnit to improve code quality Michael Lively BIRMINGHAM - MUMBAI Instant Hands-on Testing with PHPUnit How-to Copyright © 2013 Packt Publishing All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews. Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing, and its dealers and distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book. Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information. First published: May 2013 Production Reference: 1170513 Published by Packt Publishing Ltd. Livery Place 35 Livery Street Birmingham B3 2PB, UK. ISBN 978-1-78216-958-1 www.packtpub.com Credits Author Project Coordinator Michael Lively Michelle Quadros Reviewers Proofreader Brian Feaver Lydia May Morris Adam Englander Production Coordinator Melwyn D'sa Acquisition Editor Mary Jasmine Nadar Cover Work Melwyn D'sa Commissioning Editor Yogesh Dalvi Cover Image Aditi Gajjar Technical Editor Worrell Lewis About the Author Michael Lively has worked in a variety of roles in the software development industry for 12 years, from developer to architect and now a software development director. He has worked on a variety of different projects and a variety of different technologies over that time, from small home-grown sites serving a handful of regular users to large enterprise platforms serving millions of consumers. In addition to his professional work, he has been an active member of the PHP open source community. Some of his contributions include the database extension for PHPUnit and more recently an alternative mocking framework for PHP called Phake. I would like to thank everyone who, over the years, has given me opportunities to work in and with the technology industry. From my schooling to the present day I have had the fortunate blessing of meeting some of the most gifted and knowledgeable folks in the IT industry. Specifically, I would like to thank Sebastian Bergmann who introduced me to unit testing and provided me great opportunities to contribute back to the community. I would also like to thank Brian Feaver and Adam Englander. Both are fantastic co-workers and gave me lots of great feedback when I discussed topics for this book with them. Last but certainly not least this journey called life would not be nearly as complete without my girls. I would like to thank my wonderful wife Sharon and my fantastic girls Trinity, Hannah, and Gracelyn. Their patience and willingness to chase my goals with me has made all the difference in the world. About the Reviewers Brian Feaver is the Lead Software Architect at Selling Source LLC. He's been a software developer for over 10 years, contributes to multiple open source projects, and participates in developer-user communities. He is a strong advocate of developer testing and automated testing in general. Adam Englander is the CTO of Coupla where he leads their development and cloud platform initiatives. He is an accomplished software professional with more than 25 years of architecting and developing critical business systems. He is a testing evangelist and resource to the development community. He develops testing tools and, in addition, speaks to various groups about these tools and the testing methodologies in general. Coupla is an online community with the singular goal of making stronger couples relationships. Coupla is a proud member of Vegas Tech and the Las Vegas Startup Community. www.PacktPub.com Support files, eBooks, discount offers and more You might want to visit www.PacktPub.com for support files and downloads related to your book. Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at [email protected] for more details. At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters and receive exclusive discounts and offers on Packt books and eBooks. http://PacktLib.PacktPub.com Do you need instant solutions to your IT questions? PacktLib is Packt's online digital book library. Here, you can access, read and search across Packt's entire library of books. Why Subscribe? f Fully searchable across every book published by Packt f Copy and paste, print and bookmark content f On demand and accessible via web browser Free Access for Packt account holders If you have an account with Packt at www.PacktPub.com, you can use this to access PacktLib today and view nine entirely free books. Simply use your login credentials for immediate access. Table of Contents Preface 1 Instant Hands-on Testing with PHPUnit How-to 7 Installing PHPUnit (Simple) 7 Writing your first test (Simple) 9 Running tests (Simple) 12 Configuring PHPUnit (Simple) 14 Adding PHPUnit to your project (Simple) 16 Generating tests from code (Advanced) 18 Using test fixtures (Simple) 24 Using data providers (Intermediate) 26 Using test dependencies (Advanced) 29 Using mock objects (Simple) 33 Testing abstract classes (Intermediate) 44 Testing traits (Intermediate) 47 Testing exceptions and errors (Intermediate) 48 Testing output (Intermediate) 50 Testing protected and private methods (Intermediate) 52 Testing database interaction (Advanced) 55 Viewing code coverage (Advanced) 66 Preface The goal of almost every software developer is to create code that is free from defects and works as intended. To help ensure this goal is met we spend a significant amount of time testing the code that we have written. As software grows in size and complexity the likelihood of defects being introduced increases. Naturally, we have to increase our efforts in testing to help accommodate the increased risk. When I first began writing software I would test my applications by manually running through a series of steps on a deployed application. I would add items to my cart, I would remove them again, I would manually check to make sure taxes and shipping costs were calculated correctly. I spent a lot of time looking at as much functionality as I could think of. Commonly, I would miss some less obvious pieces of functionality and small bugs would slowly creep into the code as the software aged and my memory of the intricate details of how it worked faded. Fortunately, I was introduced to the concept of automated testing fairly early on in my career. Automated testing, specifically automated unit testing is a powerful tool in any programmer's arsenal. It allows us to have an easily repeatable way to check and make sure the software we write is working the way we intend. It provides future maintainers of the code with the ability to have confidence that they can change functionality and not be worried that they will regress the code back to old errors. It gives us freedom as software developers to focus more time on moving our software forward instead of living in fear that any change we make will cause the system to break. There are many tools to help you write effective unit tests quickly. In PHP, the leading tool is PHPUnit. In this book, we are going to learn how you can use PHPUnit in your project to create a test suite that can give you an increased level of confidence in the software you are writing. What this book covers Installing PHPUnit (Simple) will teach you how to install PHPUnit using the PEAR package manager. You will also learn about some alternative ways to install PHPUnit. Writing your first test (Simple) will help you create a basic test and learn about the common phases of a unit test written in PHPUnit.