Symfony - Unit Testing


Advertisements


Unit test is essential for ongoing development in large projects. Unit tests will automatically test your application’s components and alert you when something is not working. Unit testing can be done manually but is often automated.

PHPUnit

Symfony framework integrates with the PHPUnit unit testing framework. To write a unit test for the Symfony framework, we need to set up the PHPUnit. If PHPUnit is not installed, then download and install it. If it is installed properly, then you will see the following response.

phpunit 
PHPUnit 5.1.3 by Sebastian Bergmann and contributors

Unit test

A unit test is a test against a single PHP class, also called as a unit.

Create a class Student in the Libs/ directory of the AppBundle. It is located at “src/AppBundle/Libs/Student.php”.

Student.php

namespace AppBundle\Libs; 

class Student { 
   public function show($name) { 
      return $name. “ , Student name is tested!”; 
   } 
}

Now, create a StudentTest file in the “tests/AppBundle/Libs” directory.

StudentTest.php

namespace Tests\AppBundle\Libs; 
use AppBundle\Libs\Student;  

class StudentTest extends \PHPUnit_Framework_TestCase { 
   public function testShow() { 
      $stud = new Student(); 
      $assign = $stud->show(‘stud1’); 
      $check = “stud1 , Student name is tested!”; 
      $this->assertEquals($check, $assign); 
   } 
}

Run test

To run the test in the directory, use the following command.

$ phpunit

After executing the above command, you will see the following response.

PHPUnit 5.1.3 by Sebastian Bergmann and contributors.  
Usage: phpunit [options] UnitTest [UnitTest.php] 
   phpunit [options] <directory>  
Code Coverage Options:  
   --coverage-clover <file>  Generate code coverage report in Clover XML format. 
   --coverage-crap4j <file>  Generate code coverage report in Crap4J XML format. 
   --coverage-html <dir>     Generate code coverage report in HTML format. 

Now, run the tests in the Libs directory as follows.

$ phpunit tests/AppBundle/Libs

Result

Time: 26 ms, Memory: 4.00Mb 
OK (1 test, 1 assertion)


Advertisements
E-Books Store