Back to Top

PHPUnit Basic Tutorial

Updated 3 August 2015

PHPUnit: PHPUnit provides a simple framework for creating a test suite to automate testing of functions and classes.

One of the rules of XP is to test small software components as often and early as possible, this way you will not have to fix bugs and errors in the API while setting up and testing larger applications which depend on the class.While unit testing is one of the fundimental rules in XP, you don’t have to switch to XP to benefit from PHPUnit. PHPUnit stands alone as a good tool for testing classes or a set of functions and will ease your development cycle and help you to avoid endless debug sessions.

Current Work routine (without PHPUnit):  Normally, you would write a class, do some unsystematic tests using echo() or var_dump(). After this, you use the class in your application and hope everything is ok.

Test by using PHPUnit: To benefit from PHPUnit you should rethink the flow. The best way is to do this:

Start your headless eCommerce
now.
Find out More

1. design your class/API
2. create a test suite
3. implement the class/API
4. run the test suite
5. fix failures or errors and go to #4 again

=> It may seem that this will require a lot of time, but this impression is wrong. Creating the test suite using PHPUnit needs only a few minutes and running the test suite only seconds.

How To Install

➜ wget https://phar.phpunit.de/phpunit.phar
➜ chmod +x phpunit.phar
➜ mv phpunit.phar /usr/local/bin/phpunit

For check version
➜ phpunit ­­version

How To Run Test Class

phpunit /path/RemoteConnectTest.php

/* RemoteConnectTest.php is test class file which i made for test */

Output

➜ PHPUnit 3.4 by Sebastian Bergmann
➜ .
➜ Time: 1 second
➜ Tests: 1, Assertions: 1, Failures 0

output Definition

For each test that’s run, you’ll either see a

period (.) if it’s successful (as above),
an “F” if there’s a failure,
an “I” if the test is marked as incomplete, or
an “S” if it’s been marked as skipped.
an “E” if it’s been marked as  error occurs while running the test method.
an “R” if it’s been marked  as risky.

Key points for remember

For test class

=>extends PHPUnit_Framework_TestCase class
=>make setUp() for assign values in variable before test function run //optional
=>make tearDown() for unset values of variable after test function run done //optional
=>make test function with name that start with test
=>Each function for test pass in $this­>assertTrue();

. . .

Leave a Comment

Your email address will not be published. Required fields are marked*


1 comments

  • 454t
  • Back to Top

    Message Sent!

    If you have more details or questions, you can reply to the received confirmation email.

    Back to Home