I am using PHPUnit for quite sometime now. Though was thinking few times to write about it, but it didn’t happen till now. In fact, this is my first tutorial on testing as well. The official documentation/getting started guide is already quite good for starting. However, I personally find it a little insufficient in several cases and could be little hard to start with as a beginner. Thus, I am writing this PHPUnit tutorial to explain it as easily possible with my preferred/recommended way to start using PHPUnit. Also, though this is a beginners level tutorial on phpunit, I assume you know/have sound concept about what unit testing is!
Alternative To PHPUnit:
There is another simpletest for PHP, which you can checkout as well if you want. However, though I haven’t practically used it yet, but seems it doesn’t have as much support/flexibility as PHPUnit. Also, even being PHPUnit unofficial, still it’s almost being used everywhere, so sticking with it is a good idea, I guess.
Installing PHPUnit:
It is possible to get PHPUnit installed for per project basis or system wide as well. I personally prefer per project basis most. Lets installed this way using composer:
{ "require": { "phpunit/phpunit": "dev-master" } }
Even if you are not using composer for you project, you can have it there without affecting anything else and use its CLI comfortably. In case you are not familiar with composer, get it installed easily on your system, copy the above JSON to a file named ‘composer.json’ on your project directory and run ‘composer update’ command. And you should be done.
Now, to verify the installation, use your terminal/command line tool and go to your project directory. Then run the following command:
$./vendor/bin/phpunit PHPUnit 4.1.3 by Sebastian Bergmann. Usage: phpunit [options] UnitTest [UnitTest.php] phpunit [options] <directory> Code Coverage Options: ..............
If all OK, you should get some output as like above.
Initial PHPUnit Configuration:
Well, it’s not mandatory to maintain a configuration file. You can run specific PHPUnit class/method right from your CLI . However, I like, prefer and will strongly recommend to have a configuration file with all details so that you can just run “phpunit” command and it itself take care of the rest.
Yes, if there is a configuration file named ‘phpunit.xml’, it’s automatically read by the library and act accordingly. A sample configuration file is as below:
<?xml version="1.0" encoding="UTF-8"?> <phpunit bootstrap="./tests/bootstrap.php" convertWarningsToExceptions="true" convertNoticesToExceptions="true" convertErrorsToExceptions="true" backupStaticAttributes="false" processIsolation="false" stopOnFailure="false" backupGlobals="false" syntaxCheck="false" colors="true"> <testsuites> <testsuite name="HelloWorld Test Suite"> <directory>./tests/</directory> <file>./path/to/file.php</file> </testsuite> </testsuites> <php> <var name="SOME_CONSTANT_CONFIG" value="Test Value" /> </php> </phpunit>
Above is a very simple XML configuration. As you can see, you can specify directories where your test files are. You can specify individual files as well. Also, here you can categorize tests into separate test suit as well. Then you can just run one specific suit from CLI.
PHPUnit HelloWorld Test Case:
Lets create a test to try out. It’s good to have tests on a separate dedicated directory, usually named as ‘tests’. Create a single php file named ‘HelloWorldTest’ and put below content in it:
class HelloWorldTest extends \PHPUnit_Framework_TestCase { function testHelloWorld() { $this->assertTrue(true); } }
Just to tell you one thing here, remember, a phpunit test method name always start with ‘test’ and then rest of the name goes one. Any method that doesn’t start with ‘test’ will be ignored by phpunit.
For this first test, remove the bootstrap option from XML configuration(as we don’t have any now). And run the following command:
$./vendor/bin/phpunit
If all are OK, you should see something like as below:
PHPUnit 4.3-g39989b7 by Sebastian Bergmann. Configuration read from /path/to/phpunit.xml . Time: 793 ms, Memory: 2.50Mb OK (1 test, 1 assertion)
As you can see, in summary output, it shows the most necessary information in brief like, how many tests(each test method is considered as single test, however a single test can include as many assertion as you need) ran. how much time/memory it took etc.
Understanding Assertion:
Assertion is the process of verifying an expected output to an actual output. This is something like this – you will provide set of input(s) to a unit of functionality(usually a specific method) in your application. Then you verify whether your desired output is same as the actual output the method returning to you. If yes, it passes the test, otherwise it fells.
There are several built-in assert* methods(which are standards on unit tests of other programming language as well) that you will be using to compare value your application is returning to the value you are expecting. Lets say, your application has a class that checks whether a user is logged in or not. This could be written in PHPUnit as below:
function testAuthorized() { $this->assertTrue(Auth::isLoggedIn()); }
In similar way you can compare two values as well:
function testPHPUnitMethod() { $company = CompanyModel::getByName("companyName"); $this->assertEqual(50, $company->noOfEmployee()); }
There are lots of other assertions available which you can use to compare almost anything you might need.
Initialization/Destruction:
Well, it might happen that, you have several test cases that need to do several common steps at the beginning. To make a common generalization of such situations, phpunit comes up with built-in support for ‘setUp’ and ‘tearDown’ method, which you can write
to do common initialization and destruction mechanisms. Example shown below:
public function setUp() { $this->db->ClearDatabase(); $this->session->start(); } public function tearDown() { $this->session->destroy(); }
Final Words:
As a getting started point, hopefully this small PHPUnit tutorial should be enough, I guess. However, if you are not clear about anything or if you think some other information will be helpful to add, please let me know via comment and I will try to add them soon. Also, I am willing to write more on this later on. Happy coding 🙂
Without class ,How to test PHP functions?
I have following simple code inside my Index.php file
So how to test only message() functin without class by using PHPUnit inside NetBeans Framework.
This will help you
http://stackoverflow.com/questions/36016250/is-it-possible-to-unit-test-php-files-other-than-class-file-using-phpunit/36016329#36016329
$this->assertEqual(50, $company->noOfEmployee());
this should be ‘assertEquals’
but further than that, everything worked thanks!
Nice guide but I think you forgot to mention that before starting the test process, a proper directory structure for the files to be tested is required (mentioned here: https://www.cloudways.com/blog/getting-started-with-unit-testing-php/ ). This way you can efficiently run the test of your code.