The use of PHPUnit PHP unit test

Recommended for you: Get network issues from WhatsUp Gold. Not end users.

PHPUnit is a PHP programming language developed by open source software, is a unit testing framework. PHPUnit created by Sebastian Bergmann, from Kent Beck SUnit, is the framework of xUnit family. This paper will explore the PHPUnit, particularly the introduction of the basic usage of automated unit testing. You need to master the basic knowledge of PHP programming language in order to continue.

Author: Kendrick Curtis, Stainless Software,


Unit testing is a process to test individual code object, such as a test function, class, method. Unit test can be used for an arbitrary period has written test code, can use the existing test frameworks, such as JUnit, PHPUnit or Cantata++, unit testing framework provides a set of common, useful features to help people write automated detection unit, such as checking an actual value is consistent with our expectations. Value assertion. Unit testing framework often contain each test report is given, and you have to cover the code coverage.


PHPUnit usually uses PEAR packet, Composer bundle or PHAR exists in the form of documents. If you want to install it, you need to install PHP Code Coverage dependent. In PEAR, you need to price the channel, and through the command line to install two pack:

PHP Unit Testing with PHPUnit

(note, in the input, the default XAMPP PEAR installation has been destroyed: you need PEAR PHAR installed first before trying the above code).

A simple test of the class

Try a simple class has only a single method:

1 class TruthTeller

2 {

3 public function() tellTruth

4 {

5 return true;

6 }

7 }

Yes, now tellTruth method always returns TRUE, then we should be how to use unit testing to ensure that future its return value unchanged?

The use of PHPUnit, each test is an extension of the class of the PHPUnit_Framework_TestCase class, which provides the common functions, such as judgment. The following is a tellTruth method for the testing of a basic:

01 require_once 'PHPUnit/Autoload.php';

02 require_once 'TruthTeller.class.php';

03 class TruthTester extends PHPUnit_Framework_TestCase

04 {

05 function testTruthTeller()

06 {

07 $tt = new TruthTeller();

08 $this->assertTrue($tt->tellTruth());

09 }

10 }

Please note, you need to include the PHPUnit automatic loader and “ &rdquo, the measured object; in this case the TruthTeller class file.

We use the rest of the code is to do, if the tellTruth method is invoked, it returns true. These judgments are the core of the PHPUnit - they will make a decision whether the test passed or failed.

If you start the command prompt, switch to your test directory, run phpunit TruthTester (parameter is your test file name, remove the.Php extension), all of which can find the test specified in the PHPUnit will run in the file (the tests will be the name to all the methods at the beginning of the test).

PHP Unit Testing with PHPUnit

If you go back to the TruthTeller class, and the method return values to FALSE, you will see similar to the following information:

PHP Unit Testing with PHPUnit

This is the core of the &mdash unit test; — write assertions and determine whether the. When the previous write and test the code to fail, you'll see a change of code has had a negative impact on existing code.

More complex test

In reality, you will need to handle more complex than the last case. For example, a common test is a outputArray method to check whether the returned array under a specific data structure.

1 class ArrayTeller

2 {

3 public function outputArray()

4 {

5 return array(1,2,3);

6 }

7 }

A simple test of this method can write this:

01 class ArrayTester extends PHPUnit_Framework_TestCase

02 {

03 function testArrayTeller()

04 {

05 $at = new ArrayTeller();

06 $result = $at->outputArray(1);

07 $this->assertInternalType("array", $result);

08 $this->assertCount(3, $result);

09 $this->assertEquals(1, $result[0]);

10 $this->assertEquals(3, $result[2]);

11 }

12 }

As you can see, using the PHPUnit unit test in each row of the diversified examination: can check whether ArrayTeller returns an array, rather than any other data type; can check the length of the array; may the single check the values in the array. In addition to these, there are some other functions such as assertion, if you need more complex judgment, assuming you know a return value interval is two whole numbers, as long as you can use a IF statement to express the results, you can use assertTrue to test the assertion. Click on the following link to access the list of all available asserts PHPUnit website document,.

class Switcher

02 {

03   public function aOrB($switch, $a, $b)

04   {

05     if ($switch == TRUE)

06     {

07       return $a;

08     }

09     else

10     {

11       return $b;

12     }

13   }

14 }

… you'll see the need to write two test, respectively, for a situation. But you begin to question how do you know these — — if the method returns for True $a, False returns $b, otherwise an exception is thrown, the ideal situation is somewhere in the document mentioned specification. In any case, the above test methods are as follows:

01 class SwitcherTester extends PHPUnit_Framework_TestCase

02   {

03     function testSwitchTrue()

04     {

05       $switcher = new Switcher();

06       $result = $switcher->aOrB(TRUE, 1, 2);

07       $this->assertEquals(1, $result);

08     }

09     function testSwitchFalse()

10     {

11       $switcher = new Switcher();

12       $result = $switcher->aOrB(FALSE, 1, 2);

13       $this->assertEquals(2, $result);

14     }

15 }

Running two test with the command line running phpunit SwitcherTester.

Using setUp, the simplified multiple test

Using the function when the input combination and data set your testing needs to cover more and more,: setUp will be very helpful. SetUp is the PHPUnit_Framework_TestCase class you can override to type in all and each test run before running code. (note, there is a simple method, tearDown, which runs — immediately in all the test after the end of — the closure of the socket and the file pointer helpful)

The following is a simple example of how to streamline the code. An attempt to rely on some object data what input method.

01 class DataTeller

02   {

03   private $data;

04   public function __construct($data)

05   {

06     $this->data = $data;

07   }

08   public function outputData($switch)

09   {

10     if ($switch == TRUE)

11     {

12       if (!empty($this->data))

13         return $this->data;

14       else

15         return FALSE;

16     }

17     else

18     {

19       return "switch off";

20     }

21   }

22 }

If you continue to approach before naive, we need to write three tests, and instantiate three DataTeller objects, each test a. However, through the setUp, we can tell the DataTellers object creation outsourcing, at least two out of 3. Only the last test requires a new DataTeller is created.

01 class DataTellerTester extends PHPUnit_Framework_TestCase

02 {

03   private $dt;

04   protected $data = "valid data";

05   function setUp()

06   {

07     $this->dt = new DataTeller($this->data);

08   }

09   function testOutputArraySwitchOff()

10   {

11     $this->assertEquals("switch off", $this->dt->outputData(FALSE));

12   }

13   function testOutputArraySwitchOn()

14   {

15     $this->assertEquals($this->data, $this->dt->outputData(TRUE));

16   }

17   function testOutputArrayEmptySwitchOn()

18   {

19     $new_dt = new DataTeller("");

20     $this->assertEquals(FALSE, $new_dt->outputData(TRUE));

21   }

22 }


PHPUnit use assertions to tell you your test code as you expected. You should have learned here, can write some simple tests to cover some of the features of relatively independent classes now. But when it comes to test some mutual interaction class, will face a real challenge. Therefore, please listen to the next time to explain, to learn how to write tests for a static class, and how to use the mock (simulated) and stubs (stub, pile point) other code object to isolate you want to test and the environment relations.

Extended reading

* PHPUnit manual
* PEAR site PHPUnit tutorial

About the author

Kendrick Curtis (Kendrick Curtis) is a ten years of experience in the Web developer. He is Stainless Software (stainless steel software) founder of the company, to provide development webpage design, special, testing and content creation. For more information please refer to the website of the company

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download

Posted by Oprah at October 27, 2013 - 7:49 PM