PHPUnit Essentials

5 (1 reviews total)
By Zdenek Machek
  • Instant online access to over 7,500+ books and videos
  • Constantly updated with 100+ new titles each month
  • Breadth and depth in over 1,000+ technologies
  1. Installing PHPUnit

About this book

The ability to write unit tests and software testing have become skills that every PHP developer should master.

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.

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.

Publication date:
May 2014
Publisher
Packt
Pages
314
ISBN
9781783283439

 

Chapter 1. Installing PHPUnit

To be able to write and run PHPUnit tests, PHPUnit has to be installed on the machine. With the right approach, it is not difficult; however, in the past, this was a bit of an issue for many users because they were struggling with the right settings and all of the dependencies that needed to be installed.

Until recently, the recommended installation method for PHPUnit was by using PEAR; however, from PHPUnit 3.7 onwards, there is an option available to use Composer. Composer is a tool for dependency management in PHP, which makes PHP tools or libraries' installations much easier. There are a few more options to install PHPUnit, and this chapter describes them step by step.

Apart from what is required for PHPUnit installation, this chapter also describes the Xdebug installation process. This is optional, but this PHP extension really helps with processes such as remote debugging, code coverage analysis, and profiling PHP scripts. Later in the book, how to use Xdebug for debugging and generating code coverage will be explained, and it is more than an option for every PHP developer to have this extension.

This chapter describes how to install PHPUnit, and mentions what is required to be able to run PHPUnit tests; some of these tests are as follows:

  • PHP CLI: This is a PHP command-line interface to run tests from the command line

  • PHPUnit: This is a testing framework and tool for unit tests execution

  • Xdebug: This is a PHP extension for remote debugging, code coverage, and much more

This chapter covers various PHPUnit installation methods, among which the easiest is the Composer or PEAR installation, but there are other installation methods available too. The following are the different PHPUnit installation methods:

  • Composer installation

  • PEAR installation

  • Linux package installation

  • Manual installation

As an extra step, it is recommended that you have Xdebug installed. Xdebug is a PHP extension that provides debugging and profiling capabilities and is also used by PHPUnit. Xdebug installation and configuration is described at the end of this chapter.

Note

On 21st of April, 2014, it was announced end of life for the PEAR installation method. PEAR installation should be available during the entire 2014. However, recommended installation methods are the Composer installation or PHAR archive.

 

Requirements


A developer who starts with PHPUnit is probably already working with PHP and has already installed the web server with PHP support such as Apache, NGINX, or IIS. It is strongly recommended that you use at least PHP 5.3.3 or higher; older PHP versions are not supported and maintained anymore.

Note

Information about PHPUnit and downloads and documentation can be found on the official PHPUnit site at http://phpunit.de.

PHPUnit is a unit testing framework written in PHP, but PHPUnit tests are not usually executed on a web server but through the PHP CLI—the PHP command-line interface. Through PHP CLI, the PHP script can be run as any other shell script.

Running PHP from the command line

As mentioned earlier, PHP CLI allows to run any PHP script from the command-line interface. Whichever tool is used to run PHPUnit tests, even if it has used the IDE, which seems to have everything preinstalled, it will always call PHP CLI in the background.

You can install PHP CLI as a package (PHP5-CLI), or you can find it already installed with the web server package. Even software packages such as WAMP or XAMP have it there, but you might need to specify a path to web server binaries to environment variables to be able to run PHP from the command line anywhere on your machine.

To test if PHP CLI is installed on your machine, run the following command line:

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

This is a simple Hello, World! code executed and outputted by the command language interpreter, but it confirms PHP CLI is present and does what is expected. If you see an error message such as command not found, it implies PHP CLI is not installed or the system path is missing—a path to the PHP binary.

Note

CLI may use a different php.ini configuration file than the one your web server uses. If so, you'll need to configure your PHP extensions and other bits and bobs in there separately. To check this, you can run the following command line:

> php -i

It will output a result of the phpinfo() function, but in a text version, where you will be able check configuration settings. If you have problem reading so many lines, try to output it in a text file, which you can open in a text editor, and search for the desired result. The output also can be captured in the text file, which can be easily read with any text editor.

 

Composer – the dependency manager for PHP


Composer is a tool for dependency management in PHP. It allows you to declare the dependent libraries that the project needs, and it will install them. There is a configuration file called composer.json, which, as the name suggests, is a JSON format file. This is where you set the components/libraries and version your project will be using. When you run Composer, the Composer tool not only downloads all the required libraries, but also all the other required third-party libraries used. It also creates autoloader (the file to load all required classes), and all the hard work is done—everything that is required is ready to be used.

Composer is one of the best tools available for the PHP developers. It really helps and makes your life easier. It is something that was already available in other languages such as Maven for Java or Gems for Ruby and was missing in PHP. The best thing is, in this way, you can not only manage third-party libraries and packages, but also your own libraries.

Installing Composer

The Composer tool is just one file—composer.phar. The .phar file means a PHP archive (the PHAR file) similar to the JAR files of Java. All PHP files are packed in one archive file. You can download composer.phar from http://getcomposer.org/download/ or by running the following command line:

curl -sS https://getcomposer.org/installer | php

If you haven't got curl installed, alternatively run the following command line:

>php -r "readfile('https://getcomposer.org/installer');" | php

As a result, you should see a message that composer.phar was downloaded, similar to the message displayed in the following screenshot:

Installation

There are two options that are of the biggest advantage to Composer, compared to other installation methods. Composer gives you the flexibility to specify where to store PHPUnit and also where to store the command-line script so that you can have on your machine as many versions as you want, and by using Composer, you can still maintain and keep them all up to date.

Local installation

Here is one practical example. You can specify and download PHPUnit only for your specific project. This means that when your project was developed and tested, you were working with PHPUnit version 3.5; however, for the new project, you want to use version 3.7. For example, Zend Framework 1 uses PHPUnit version 3.5; however, applications are still developed, extended, and maintained on this system even when Zend Framework 2 is available. This is not a problem as each project will have its own version of PHPUnit with all the dependencies, and there is no need to worry about clashing versions or being stacked with dated versions.

For PHPUnit installation with Composer, you have to create a composer.json file. The simplest version could look the following lines of code:

{
    "require-dev": {
        "phpunit/phpunit": "3.7.*"
    }
}

System-wide installation

The second option is a system-wide installation. Well, basically it is the same thing, except it is created by a shell script / batch file to call PHPUnit from the command line. If a file is stored in a directory set in the system path, then it is available anywhere in your system. The following lines of code represent composer.json:

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

System-wide installation might be easier in the beginning, and allows you to run tests from the command line. It's easier to start with moving composer.phar to the project document root—the same place where the composer.json file is stored. Then, to install PHPUnit, just run the following command line:

> php composer.phar install

Composer explores the composer.json file and determines all the extra packages that need to be downloaded and installed. This should display a similar result as shown in the following screenshot:

This means PHPUnit was successfully installed, including the required dependencies (YAML) and basic plugins. The line that suggests installing ext-xdebug means that you should install the PHP Xdebug extension, because it is a useful thing for development and also PHPUnit uses it to generate code coverage.

 

Installing PEAR


Another way to install PHPUnit is to use PEAR—the framework and distribution system for reusable PHP components. PEAR has been available since the early PHP 4 days, and more than a framework, it is just a set of useful packages and classes. Also, it is a distribution system for installing and keeping these packages up to date. The first step of installation is to install PEAR. Download the PHP archive file go-pear.phar from http://pear.php.net/go-pear.phar.

Similar to composer.phar, it is a PHP archive file that contains all that you need. Installation is simple, just run the following command line:

> php go-pear.phar

Follow the PEAR install instructions, hitting Enter to accept the default configuration as you go. After installation, you can test it by running PEAR from the command line by just running the following command line:

> pear

You should see something similar to the following message that will tell you where the PEAR script is stored:

The 'pear' command is now at your service at /root/pear/bin/pear

If it doesn't work, checking the installation message usually gives a clue as to where the problem is; this is shown in the following message:

** The 'pear' command is not currently in your PATH, so you need to
** use '/root/pear/bin/pear' until you have added
** '/root/pear/bin' to your PATH environment variable.

PEAR installation has one disadvantage compared to the Composer installation: it is a system-wide installation, which means you have just one version of PEAR—one version of PHPUnit installed in your system.

PHPUnit installation

When PEAR is successfully installed, PHPUnit installation is simple and straightforward, as shown in the following command line:

>pear config-set auto_discover 1
>pear install pear.phpunit.de/PHPUnit

The first line means that PEAR checks and installs the required dependencies. The sources are called channels that will be automatically discovered and added. With older versions, you had to do it manually; however, it is not necessary anymore with auto_discover. The second line then installs the latest stable version of PHPUnit. The result should be similar to the following screenshot:

 

Other installation methods


Along with the two methods that have been mentioned and recommended, there exist another two. It is up to you to choose the installation method that suits you the best (just be careful what you are installing and from where). If there is no specific reason, it's recommended choosing a stable version, and if possible the latest version. The clue could be which version is in the current PHPUnit manual, which can be found at http://phpunit.de/manual/current/en/index.html.

Installing the Linux package

For Linux users and users using Linux based virtual machines such as Vagrant and VirtualBox (Mac OS X, Windows), probably the fastest and least painful installation method is to use package manager. It depends on your Linux version, and the package management tool could be yum, apt or aptitude. Run the following command line:

>apt-get install phpunit

This will install all the required dependencies and libraries, and the result should be similar to the following screenshot:

If this is so easy, why is it not mentioned as the first installation method? Obviously, you can't use it if you are running PHP. It can't be used on Windows or Mac OS X, but there is something else. When this chapter was written, the latest available stable PHPUnit version for Composer and PEAR was 4.0. In comparison, for the Ubuntu Precise Pangolin package 3.5.5-2 version was available, Debian had version 3.6.10-1 for PHPUnit, and EPEL had PHPUnit-3.7.19-1.e16. This is something to watch out for. Some Linux distributions are very mature and very stable, but they stick to the package version that was available when the distribution was released. Then the distribution is supported for the next five years, but the package is never upgraded (just the security fixes are back-ported to the original version). This leads to situations where you have all the updates installed but still see hopelessly old versions of your tool/library.

Manual installation

The final option is manual installation. It is not too bad. There is one option that allows you to get PHPUnit with all that you need but without all the package management hassle. Just download the phpunit.phar archive from the PHPUnit site at https://phar.phpunit.de/phpunit.phar.

The package contains PHPUnit and all the required dependencies. To test, just run the following command line:

>php phpunit.phar –version

Or, you can create the phpunit executable by running the following commands:

>chmod +x phpunit.phar
>mv phpunit.phar /usr/local/bin/phpunit

Or, on Windows using phpunit.bat from the Git repository, which is also the last option, download PHPUnit source code directly by cloning the Git repository on GitHub by running the following command line:

>git clone https://github.com/sebastianbergmann/phpunit/
 

Testing the installation


When PHPUnit is installed, you should be able to run the PHPUnit tool from the following command line:

> phpunit

And then you should see a list of all the available options like the following list displayed:

PHPUnit 3.7.28 by Sebastian Bergmann.

Usage: phpunit [switches] UnitTest [UnitTest.php]
       phpunit [switches] <directory>

If it doesn't work, don't panic; try to think what might be wrong. Is the PHPUnit script on the system path? Have you installed it as user or root?

In the worst case scenario, you can try alternative installation methods or install it as a local installation just for one user. This means that all the files are going to be stored in the user home directory, and when you want to run PHPUnit, just go to phpunit/bin and there is the script. The difference with the system-wide installation is just that the files are stored in different places and PHPUnit is not added to the system path.

Anyway, now we would like to see a bit more. So, let's create our first tests and run it by using the freshly installed PHPUnit.

The best way to try PHPUnit is to create a simple unit test and execute it by using the freshly installed PHPUnit. Let's try basic mathematical operations to see if PHP counts correctly. Later, we will talk about tests syntax, but for now, let's not worry about it. There are just a few extra lines of wrapping code in class and test methods, as shown in the following code snippet:

<?php

class FirstTest extends PHPUnit_Framework_TestCase {

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

    public function testMultiplication(){
        $this->assertEquals(10, 2 * 5);
    }
public function testDivision(){
        $this->assertTrue(2 == (10 / 5));
    }

}

Tip

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.

Let's save it into FirstTest.php and then run it using the following command line:

> phpunit FirstTest.php

And then we see the result as shown in the following screenshot:

Brilliant, it works!

Works, but it says one failure? And it's correct. This example shows you why it is important to run tests. Even things that seem obvious and appear to have no reason to be tested might not be as straightforward as you think.

Let's change the problematic line 10 with the following line of code:

$this->assertEquals(0.17, 1 – 0.83);

Now run the test again. The result now should be as shown in the following command line:

OK (4 tests, 4 assertions)

If you wonder why the previous test failed, it was that type float and floating point numbers have limited precision, so they are not exactly equal. The second number is approximately 0.1699999999999, but when the assertion method was changed to equals, PHPUnit is able to detect and handle it correctly.

Xdebug

As mentioned earlier, Xdebug is not required, but it is really recommended that for development and for running PHPUnit tests, you should install this brilliant PHP extension created by Derick Rethans. The following are killer features of Xdebug:

  • Remote debugging: This allows to stop code execution, step line by line through the code execution, watch variables, and much more.

  • Code coverage analysis: This tells you which lines were executed. This is important for testing to know if all code is covered by tests or how much is missing.

  • Code profiling: During the code execution, it is measured how much time and how much resource each class, method, and function needs. This is handy when you need to identify bottlenecks in your application.

Another similar option is Zend Debugger that is pre-installed in Zend Server, but Xdebug provides better support for code coverage, profiling, and so on.

Installation is the same as any other PHP extension. If you are not using package manager, the tricky bit could be to figure out which one is the right one for you. On the other hand, if you have installed the web server bundle, it might be already there; check the extension directory or phpinfo() output.

Installing Xdebug

If Xdebug is not installed, the following are three installation options available for it:

  • Use the precompiled binary version of Xdebug. This version needs to match your PHP version. The http://xdebug.org/download.php link contains lots of Windows binaries. It is necessary to have the correct PHP version, the compiler that was used for your installation (VC6, VC9, VC11), and if you have it, the thread-safe installation. You can see all of these things in phpinfo() output. On Linux, it is much easier to install if you use your package manager. For example, run the following command line:

    >apt-get install php5-xdebug
    
  • PECL installation (for instructions on how to install PECL, see the PEAR installation section discussed earlier). If you have PECL installed, just run the following command line:

    pecl install xdebug
    
  • Use compiling extension from the source code to install Xdebug. This method is only recommended for experienced users.

To enable the extension, you have to add the following extra line to the configuration file:

zend_extension="/usr/local/php/modules/xdebug.so"

Note

The path in the configuration file needs to be an absolute path, not a relative one as it is for other PHP extensions.

To check whether the extension is installed correctly and loaded by PHP, just run the following command line:

>php --version

If extension is loaded, you should see an output similar to the following screenshot:

 

Summary


There are several ways to install PHPUnit. This chapter showed all the available options. The Composer and PEAR installation methods are recommended as they can handle all the required dependencies and allow to keep PHPUnit and the required libraries up to date. PHPUnit installation is not difficult if the right path is followed. Xdebug extension is optional, but it is strongly recommended that you install it as we will need extra features such as remote debugging and code coverage later.

When writing and running PHPUnit tests, it's really important to have a good IDE (Integrated Development Environment). All modern IDEs have good PHPUnit support. The next chapter will show the four most popular IDEs in PHP world. We will also see how to configure them, how to execute tests, and how to debug tests. Good support for PHPUnit and PHP in general is something that makes a developer's life much easier, and he/she is able to produce good code much faster than using an ordinary text editor.

To have PHPUnit installed is the first good step. In the next chapter, before jumping to writing tests, it's good to have a look at how to run and debug PHPUnit tests in IDE such as Zend Studio and NetBeans.

About the Author

  • Zdenek Machek

    Zdenek Machek is an experienced PHP developer, who has been working with PHP since the year 2000 and PHP3 days. He introduced software testing and PHPUnit to various companies, and used them on various small as well as large scale projects.

    Zdenek wrote several articles and blog posts focused on Continuous Integration processes during PHP application development.

    Currently, Zdenek leads technology standards and values across the organization, and also handles analysis, planning, and technical delivery of large scale, critical, and high performance systems for our most complex projects.

    Browse publications by this author

Latest Reviews

(1 reviews total)
Great book - a mush have for learning testing
Book Title
Unlock this full book FREE 10 day trial
Start Free Trial