In previous post PHPUnit Basic Tutorial we learned overview of PHPUnit.
Now in this post we Write a test class and execute it and read output of test result.
Step 1#: Create a test class named as SampleClass in file named SampleClass.php
this class contain a method for division of two numbers
<?php class SampleClass { public function divideNumber($a=null,$b=null){ $c=$a/$b; return $c; } } ?>
Step 2#:now we write a test named SampleClassTest in file named SampleClassTest.php
for above class
<?php require_once('SampleClass.php');/* include file which you want to test*/ class SampleClassTest extends PHPUnit_Framework_TestCase { protected $dataarr1=array(); /* PHPUnit supports sharing the setup code. Before a test method is run, a template method called setUp() is invoked. */ public function setUp(){ /*setUp() is where you create the objects against which you will test. */ $this->dataarr1=array(5,6,7,8,9); } /* Once the test method has finished running, whether it succeeded or failed, another template method called tearDown() is invoked. */ public function tearDown(){ /* tearDown() is where you clean up the objects against which you tested. */ $this->dataarr1=""; } /* in below method we pass all element of $this->dataarr1 and counter $i value */ public function testMyObject(){ // test to ensure that the object from addNumber is valid $connObj=new SampleClass();/* create object of class which you want to test */ for($i=1;$i<5;$i++){ /*here value of $i is from 1 to 5 so it run successfully*/ $this->assertTrue($connObj->divideNumber($this->dataarr1[$i],$i) !== false); } } public function testMyObjectnext(){ $connObj=new SampleClass(); for($i=0;$i<5;$i++){ /*here value of $i is from 0 to 5 so it return error Division by zero */ $this->assertTrue($connObj->divideNumber($this->dataarr1[$i],$i) !== false); } } } ?>
For run test class
$ phpunit SampleClassTest.php
output
PHPUnit 4.7.6 by Sebastian Bergmann and contributors.
.E
Time: 76 ms, Memory: 11.50Mb
There was 1 error:
1) SampleClassTest::testMyObjectnext
Division by zero
/home/users/webkul/www/html/phpunit/SampleClass.php:5
/home/users/webkul/www/html/phpunit/SampleClassTest.php:25
FAILURES!
Tests: 2, Assertions: 4, Errors: 1.
test method “testMyObjec()” of class “SampleClassTest” executed successfully so in output we get period (.) that indicate successfully execution of test method.
and for method “testMyObjectnext()” of class “SampleClassTest” execution we get “E” which indicate error occurs while running the test method. also we get detail about error in output.
5 comments
My support period has already been expired so i can’t submit ticket for Webkul, but it’s the bug so I think it should be fix by webkul, please tell me how to solve it. My email is [email protected] thx.