6. Writing Unit Test
● Class must extends PHPUnitFrameworkTestCase class
● Class Name must suffixed with “Test” e.g. NumberTest
● All testing function must be prefixed with “test” e.g. function testAdd()
● All testing functions must be public.
7. Writing Unit Test : Sample Source Code
class Add {
public function add($x, $y) {
return $x+$y;
}
}
8. Writing Unit Test : Actual Test
class AddTest extends PHPUnitFrameworkTestCase {
public function testAdd(){
$no1 = 1;
$no2 = 2;
$addObj = new Add;
$result = $addObj->add($no1, $no2);
$this->assertEquals( 3, $result);
}
}
10. Php Unit Characters
. Printed when the test succeeds.
F Printed when an assertion fails while running the test
method.
E Printed when an error occurs while running the test
method.
R Printed when the test has been marked as risky
S Printed when the test has been skipped
11. Assertions
PHPUnit's assertions are implemented in PHPUnitFrameworkAssert.
PHPUnitFrameworkTestCase inherits from PHPUnitFrameworkAssert.
● assertTrue
● assertFalse
● assertEquals - ignore data type
● assertSame - checks data type
● assertInstanceOf
○ - e.g. $this->assertInstanceOf(Add::class, $addObj);
● assertEmpty
● assertNull
● assertFileExists
...
12. Annotations
An annotation is a special form of syntactic metadata that can be added to the source
code of some programming languages.
● @depends - depends on output of the other function
● @dataProvider - depends on test cases
13. Some Best Practices
Best practices in Unit Testing are:
· Unit Test cases should be independent. In case of any enhancements or change in
requirements, unit test cases should not be affected.
· Test only one code at a time.
· Follow clear and consistent naming conventions for your unit tests
· In case of change in code in any module, ensure there is a corresponding unit test case
for the module and the module passes the tests before changing the implementation
· Bugs identified during unit testing must be fixed before proceeding to the next phase in
SDLC
· Adopt a "test as your code" approach.