Running tests (Simple)
Now that we know how to write tests it is time to learn how to run them. We will run our tests using the phpunit
script. It provides very easy to understand output that shows you whether or not your tests have passed or failed. It also provides a wealth of very useful command line options. We will go over the essential options in this recipe.
How to do it...
Execute the following command from your test project:
$ phpunit CardTest.php
You should see the following result:
How it works...
The simplest form of PHPUnit is to pass the filename of the test you want to run as the only parameter. This will cause PHPUnit to load its framework, then it will load your test and execute each method in the test case you specified.
There's more...
You can also pass a directory to the phpunit
script. If you do this, PHPUnit will scan that directory, along with any child directories. Any file with a name in the *Test.php
format will then be scanned. Any class found in that file that extends PHPUnit_Framework_TestCase
will be executed as a test. So if we had, instead, run the following command we would see the exact same output:
$ phpunit .
This command would find the CardTest.php
file. After scanning that file it would find the CardTest
class and proceed to execute it as a test case.
This functionality, in addition to an intelligent directory structure for your code and tests, can yield a very easy way for you to run small groups of tests at a time. This is something that can be helpful when making small, localized changes to a large code base.
Command line options
The previous example is a very simple. However, there are several command line options that you can use to produce more details about the tests, modify the output of the test, or to specify exactly which tests to run. If you run phpunit -h
, you will see a list of the available options. While you should spend some time looking at all of these options, you can begin by learning how to use those shown as follows:.
--colors
This option makes it obvious very quickly via a color bar whether or not your tests passed or failed. An example of what this looks like can be seen in the following screenshot:
--stop-on-error and --stop-on-failure
These options will halt the test execution if one of your tests fails or has an error. If you have a large test suite and you don't want to run through the full suite when a test fails, these options can be very helpful.
--debug
This will print the name of each test as it is being run. This can be very useful if there are severe issues causing PHPUnit to crash.
--strict
This will enable some additional checks to make sure you don't have any potential issues with your tests. For instance, it will report an error if you have defined a test case with no tests, or if a test outputs any text.