Book Image

PHPUnit Essentials

By : Zdenek Machek
Book Image

PHPUnit Essentials

By: Zdenek Machek

Overview of this book

<p>The ability to write unit tests and software testing have become skills that every PHP developer should master.<br /><br />This book is a practical guide to PHPUnit and unit testing, covering all aspects of writing PHPUnit tests and using them. The book shows why testable code is better code and how to write good tests with the help of simple and easy-to-understand examples.<br /><br />With this book, you will learn how to write, organize, and execute effective tests. Step-by-step techniques of how to write testable code, how to refactor the code, and how to run your tests are shown. You will also learn about advanced testing techniques, including how to test databases, APIs, and legacy code. PHPUnit Essentials is a guide for PHP developers who want to learn or improve their software testing skills. It is a book for developers who begin with testing but is also a good source of information for developers who are already familiar with PHPUnit.</p>
Table of Contents (21 chapters)
PHPUnit Essentials
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
5
Running Tests from the Command Line
Index

Preface

In the last ten years, PHP as a programming language has made great progress. It has evolved from a simple scripting language to a powerful platform, powering some of the busiest websites on the Internet, such as Wikipedia and Facebook. It has grown from an ugly duckling to a beautiful swan, and some statistics say that 75 percent of the Internet these days is powered by PHP.

Many sites began as simple PHP scripts, which were successful and grew—more users and transactions. Yet a simple scripting language wasn't enough. For example, object-oriented programming was introduced in PHP 4, which was completely rewritten in PHP 5 with the usage of design patterns such as MVC (Model-View-Controller), event-driven programming, and much more. Things are not simple anymore; everything became more complex and also more difficult to understand. However, applications have become quicker to build by reusing already existing components without the need to reinvent the wheel again and again. Also, the developers are able to work with the code that they haven't seen before, and they are able to extend and modify this code.

What seems to be simple on paper is not simple in the real world. There exists complexity and dependency in the code, and this is exactly where the problem lies. The more complex the code, the bigger the chance it will break. This even has a name CRAP (Change Risk Analysis and Predictions) index. The CRAP index shows how difficult it will be to maintain and extend a certain code and how likely it is that new bugs can occur.

So what can you do to minimize the possible problems? The answer is unit testing. Simply, try to split your code into units (such as cells), which you can test independently, then test that every small bit for its desired actions. In the PHP world, it has become standard to have a PHPUnit, library, and framework written by Sebastian Bergmann for PHP code automated testing. The API is very similar to any other xUnit framework, such as the JUnit in Java world or NUnit in the .NET world.

What this book tries to show and teach you is how to write better and more predictable code, and PHPUnit and automated testing is great way to start.

But this book is not theoretical. The focus is on practical PHPUnit usage. While the PHPUnit is a great cornerstone, a cornerstone is not enough to build a house. This book helps you learn what a PHPUnit is and to write unit tests, but with real-world examples and not just isolated theoretical ones. Automated testing is really useful when it works, and this is something that is missing in many similar books—a style where the topic is in the real world and in the everyday developer's work context. Thus, the book covers all aspects, from the very beginning on how to install and use the PHPUnit, to how to run tests and, of course, how to write tests. But the question is why should we write tests?

As mentioned earlier, it's a way to write better code. It's a way to guarantee the quality of produced code, thus minimizing the number of bugs. Every developer wants to minimize these mistakes. But then question arises, who will pay for the tests? It's extra code that needs to be written, which will cost us extra time. The answer to this question is simple. Do you care about the work that you are doing, the code that you write, or don't you?

Writing tests and setting up automated testing should be a part of any bigger project and also part of the budget.

Quickly developing a project, sticking to a very tight budget and deadline, and sacrificing all procedures, including testing is a straight way to hell. When the project is delivered, more and more bugs will be found, and any refactoring or changes in application will be problematic and expensive. These extra costs will very quickly become much more than the initial investment in automated testing and writing testable code. But the worst case is that these costs could be completely unpredictable because even a simple change in an application might return as a boomerang again and again as more and more problems are reported by customers.

Simply writing code without testing is like borrowing money on a credit card—one day you have to pay it back, and you pay it back with interest. Not investing in development procedures and quality assurance is very shortsighted and sooner or later will lead to disaster. Writing PHPUnit tests and better code is the way to make your projects and business successful.

What this book covers

Chapter 1, Installing PHPUnit, introduces you to various PHPUnit installation methods. A simple thing such as PHPUnit installation is something where many users really struggle. It is easy, but it's worth considering different options and installation methods.

Chapter 2, PHPUnit Support in IDEs, shows how to configure and use four of the most popular PHP IDEs used for writing and running PHPUnit tests.

Chapter 3, Tests and What They're All About, gives a gentle introduction to unit testing and why and when to write tests.

Chapter 4, Testing Dependencies and Exceptions, will demonstrate how to write the code in a way that can be tested because one of the biggest nightmares in testing is to test dependencies.

Chapter 5, Running Tests from the Command Line, explains how to execute tests by using the command-line test runner. Running tests from the command line is a basic yet powerful way to run tests and get good test results.

Chapter 6, Test Isolation and Interaction, describes fixtures of the tests, which are steps to create a consistent known environment where tests will behave in an expected way or will highlight any lapses from expected behavior.

Chapter 7, Organizing Tests, will describe how to organize tests, where and how to store tests, and group tests to test suites.

Chapter 8, Using Test Doubles, explains how test doubles are a really useful way to replace dependencies. There are several techniques on how to achieve an expected behavior. You can easily replace a tested object or its part through doubles.

Chapter 9, Database Testing, explains techniques that allow to test code using a database.

Chapter 10, Testing APIs, describes that the best way to implement a third-party API into your own application is to first write integration tests to see whether the API works and how.

Chapter 11, Testing Legacy Code, will show several techniques on how to test a legacy code to be able maintain and extend it. But without tests, there is no refactoring.

Chapter 12, Functional Tests in the Web Browser Using Selenium, shows how to write PHPUnit Selenium functional tests. Over the years, Selenium has become standard in functional tests, running in a web browser by imitating user's behavior. Selenium tests are just extended PHPUnit tests and definitely are an important jigsaw in the testing puzzle.

Chapter 13, Continuous Integration, describes three popular open source projects that can host and run PHPUnit tests.

Chapter 14, PHPUnit Alternatives, Extensions, Relatives, and BDD, describes several interesting projects and alternatives of PHPUnit, their differences, and advantages in comparison to PHPUnit.

What you need for this book

PHP CLI (PHP Command Line Interface) is required, which can be installed as a package or which comes with packages such as XAMP or WAMP. An installed web server such as Apache or NGINX is also recommended. PHPUnit can be installed, and it works on Linux, Mac OS X, or Windows.

The first chapter covers various PHPUnit installation methods and the reader can choose, if he or she prefers, PEAR, Composer, GIT, or manual installation.

Who this book is for

PHPUnit Essentials is a book for PHP developers. The book helps with the first steps of the unit-testing world, and teaches readers how to install and use PHPUnit. It also gives developers, who have previous experience with PHPUnit, a detailed overview about testing in the context of the continuous integration process.

Testing is definitely a skill that every good developer should master, and the book helps you understand the point of testing by using simple everyday examples and by offering practical solutions to problems that developers face every day.

Conventions

In this book, you will find a number of styles of text that distinguish between different kinds of information. Here are some examples of these styles, and an explanation of their meaning.

Code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles are shown as follows: "CLI may use a different php.ini configuration file than the one your web server uses."

The book uses a straightforward approach. Usually the problem is described and then presented in a code similar to the following:

<?php

class FistTest extends PHPUnit_Framework_TestCase {

    public function testAddition(){
        $this->assertEquals(2, 1 + 1);
    }

    public function testSubtraction(){
        $this->assertTrue(1 == (2 - 1));
    }

Any command-line input or output is written as follows:

> php -r "echo 'Hello, World!';"

Other code like Composer JSON configuration files are displayed in the same way as code:

{
    "require": {
        "phpunit/phpunit": "3.7.*"
    },
    "config": {
        "bin-dir": "/usr/local/bin/"
    }
}

New terms and important words are shown in bold. Words that you see on the screen, in menus or dialog boxes for example, appear in the text like this: "As a first step, create a new project as PHP application by navigating to the File | New Project menu."

Note

Warnings or important notes appear in a box like this.

Tip

Tips and tricks appear like this.

Reader feedback

Feedback from our readers is always welcome. Let us know what you think about this book—what you liked or may have disliked. Reader feedback is important for us to develop titles that you really get the most out of.

To send us general feedback, simply send an e-mail to , and mention the book title via the subject of your message.

If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide on www.packtpub.com/authors.

Customer support

Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.

Downloading the example code

You can download the example code files for all Packt books you have purchased from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.

Downloading the color images of this book

We also provide you a PDF file that has color images of the screenshots/diagrams used in this book. The color images will help you better understand the changes in the output. You can download this file from https://www.packtpub.com/sites/default/files/downloads/3439OS_ColoredImages.pdf.

Errata

Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books—maybe a mistake in the text or the code—we would be grateful if you would report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting http://www.packtpub.com/submit-errata, selecting your book, clicking on the errata submission form link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded on our website, or added to any list of existing errata, under the Errata section of that title. Any existing errata can be viewed by selecting your title from http://www.packtpub.com/support.

Piracy

Piracy of copyright material on the Internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works, in any form, on the Internet, please provide us with the location address or website name immediately so that we can pursue a remedy.

Please contact us at with a link to the suspected pirated material.

We appreciate your help in protecting our authors, and our ability to bring you valuable content.

Questions

You can contact us at if you are having a problem with any aspect of the book, and we will do our best to address it.