PHPUnit Prepared By:- Nikunj Bhatnagar
Content > What is unit Testing > Introduction of unit testing > How to use PHPUNIT > Advantage and Disadvantage
What is unit Testing? Unit : The smallest testable part of an application.z Unit testing : Testing a unit of code isolated from its dependencies.
Introduction Of PHPUNIT Testing with PHPUnit means checking that your program behaves as expected, and performing a battery of tests, runnable code-fragments that automatically test the correctness of parts (units) of the software. These runnable code- fragments are called unit tests.
Installing PHPUnit PHPUnit is installed using the PEAR Installer Commands to install : pear config-set auto_discover 1 pear install pear.phpunit.de/PHPUnit Or you can simply download it from git hub and save it to your htdocs/html forder.Then it will be ready to use
Writing Tests for PHPUnit The tests for a class persontest go into a class persontest. Persontest inherits (most of the time) from PHPUnit_Framework_TestCase. The tests are public methods that are named test*. Inside the test methods, assertion methods such as assertEquals() are used to assert that an actual value matches an expected value.
Functions > Define what you expect to happen > Assertions check statement is true > 36 assertions as of PHPUnit 3.6 > assertArrayHasKey() > assertContains() > assertContainsOnly() > assertCount() > assertEmpty() > assertEquals() > assertFalse()
Sample PHP class for testing //persontest.php <?php require_once'person1.php'; class persontest extends PHPUnit_framework_TestCase{ public $test; public function setup(){ $this->test=new person1('nikunj'); } public function testname(){ $nikunj=$this->test->getname(); $this->assertTrue($nikunj == 'nikunj'); }} ?>
Test class for testing user.php // person1.php <?php class person1{ public $name; public function _construct($name){ $this->name=$name; } public function getname(){ return $this->name; }} ?>
How to run the PhP unit test case Firstly Save the persontest.php and person1.php in your htdocs/html. Then open your cmd/terminal. Run command phpunit UnitTest persontest.php Runs the tests that are provided by the class UnitTest. This class is expected to be declared in the specified sourcefile.
Running our Tests root@nikunj:/var/www/test-1# phpunit persontest.php PHPUnit 3.6.10 by Sebastian Bergmann. . Time: 0 seconds, Memory: 1.70Mb OK (1 test, 1 assertion)
For each test run, the PHPUnit command-line tool prints one character to indicate progress: > . – Printed when a test succeeds. > F – Printed when an assertion fails. > E – Printed when an error occurs while running the test. > S – Printed when the test has been skipped. > I – Printed when the test is marked as being incomplete.
PHPUnit – Database Extension PHPUnit Database Extension – DBUnit Port Can be installed by : pear install phpunit/DbUnit Currently supported databases: > MySQL > PostgreSQL > Oracle > SQLite has access to other database systems such as IBM DB2 or Microsoft SQL Server Through Zend Framework or Doctrine 2 integrations
The four stages of a database test > Set up fixture > Exercise System Under Test > Verify outcome > Teardown
Configuration of a PHPUnit Database TestCase Need to Extend abstract TestCase : PHPUnit_Extensions_Database_TestCase require_once 'PHPUnit/Extensions/Database/TestCase.php'; class BankAccountDBTest extends PHPUnit_Extensions_Database_TestCase {
Configuration of a PHPUnit Database TestCase Must Implement getConnection() - Returns a database connection wrapper. getDataSet() - Returns the dataset to seed the database with.
Implementation of getConnection() and getDataset() methods <?php require_once 'PHPUnit/Extensions/Database/TestCase.p hp'; class DatabaseTest extends PHPUnit_Extensions_Datab ase_TestCase{ protected function getConnection(){ $pdo = new PDO('mysql:host=localhost;dbname=te stdb', 'root', '');return $this- >createDefaultDBConnection($pdo, 'testdb'); } protected function getDataSet(){return $this- >createFlatXMLDataSet(dirname(__FILE__).'/_files/bank -account-seed.xml'); }}?>
Test class for database testing //Filename : dbclass.php <?php class BankAccount { public function __construct($accno, $conn, $bal=0) { $this->addData(array($accno,$bal),$conn); }function addData($data, $conn) { $sql = "INSERT INTO bank_account (account_number, balance) VALUES (:acc,:bal)"; $q = $conn->prepare($sql); $q->execute(array(':acc'=>$data[0], ':bal'=>$data[1])); }}
Test case for dbclass.php <?php require_once 'PHPUnit/Extensions/Database/TestCase.php'; require_once "dbclass.php"; class BankAccountDBTest extends PHPUnit_Extensions_Database_TestCase { protected $pdo; public function __construct() { $this->pdo = new PDO('mysql:host=localhost;dbname=phpunitdb', 'root', 'root'); }
protected function getConnection() { return $this->createDefaultDBConnection($this->pdo, 'phpunitdb'); } protected function getDataSet(){ return $this- >createFlatXMLDataSet('/var/www/tests/bankaccdb/files/see d.xml'); } public function testaddData(){ $bank_account = new BankAccount('1234567', $this- >pdo); $xml_dataset = $this- >createFlatXMLDataSet('/var/www/tests/bankaccdb/files/see d-after-insert.xml'); $this->assertTablesEqual($xml_dataset- >getTable('bank_account'),$this->getConnection()- >createDataSet()->getTable('bank_account')); }}
Running the test root@nikunj:/var/www/tests/bankaccdb# phpunit dbclasstest.php PHPUnit 3.6.10 by Sebastian Bergmann. . Time: 0 seconds, Memory: 3.00Mb OK (1 test, 1 assertion)
Advantages •Testing gives code authors and reviewers confidence that patches produce the correct results. •Detect errors just after code is written. •The tests are run at the touch of a button and present their results in a clear format. •Tests run fast. •The tests do not affect each other. If some changes are made in one test, the results of others tests do not change.
Disadvantages Some people have trouble with getting started: where to put the files, how big the scope of one unit test is and when to write a separate testing suite and so on. It would be difficult to write a test for people who are not programmers or familiar with PHP.
Thank You Question. . . .? You can leave comment or Send the message.

Phpunit testing

  • 1.
  • 2.
    Content > What isunit Testing > Introduction of unit testing > How to use PHPUNIT > Advantage and Disadvantage
  • 3.
    What is unitTesting? Unit : The smallest testable part of an application.z Unit testing : Testing a unit of code isolated from its dependencies.
  • 4.
    Introduction Of PHPUNIT Testingwith PHPUnit means checking that your program behaves as expected, and performing a battery of tests, runnable code-fragments that automatically test the correctness of parts (units) of the software. These runnable code- fragments are called unit tests.
  • 5.
    Installing PHPUnit PHPUnit isinstalled using the PEAR Installer Commands to install : pear config-set auto_discover 1 pear install pear.phpunit.de/PHPUnit Or you can simply download it from git hub and save it to your htdocs/html forder.Then it will be ready to use
  • 6.
    Writing Tests forPHPUnit The tests for a class persontest go into a class persontest. Persontest inherits (most of the time) from PHPUnit_Framework_TestCase. The tests are public methods that are named test*. Inside the test methods, assertion methods such as assertEquals() are used to assert that an actual value matches an expected value.
  • 7.
    Functions > Define whatyou expect to happen > Assertions check statement is true > 36 assertions as of PHPUnit 3.6 > assertArrayHasKey() > assertContains() > assertContainsOnly() > assertCount() > assertEmpty() > assertEquals() > assertFalse()
  • 8.
    Sample PHP classfor testing //persontest.php <?php require_once'person1.php'; class persontest extends PHPUnit_framework_TestCase{ public $test; public function setup(){ $this->test=new person1('nikunj'); } public function testname(){ $nikunj=$this->test->getname(); $this->assertTrue($nikunj == 'nikunj'); }} ?>
  • 9.
    Test class fortesting user.php // person1.php <?php class person1{ public $name; public function _construct($name){ $this->name=$name; } public function getname(){ return $this->name; }} ?>
  • 10.
    How to runthe PhP unit test case Firstly Save the persontest.php and person1.php in your htdocs/html. Then open your cmd/terminal. Run command phpunit UnitTest persontest.php Runs the tests that are provided by the class UnitTest. This class is expected to be declared in the specified sourcefile.
  • 11.
    Running our Tests root@nikunj:/var/www/test-1#phpunit persontest.php PHPUnit 3.6.10 by Sebastian Bergmann. . Time: 0 seconds, Memory: 1.70Mb OK (1 test, 1 assertion)
  • 12.
    For each testrun, the PHPUnit command-line tool prints one character to indicate progress: > . – Printed when a test succeeds. > F – Printed when an assertion fails. > E – Printed when an error occurs while running the test. > S – Printed when the test has been skipped. > I – Printed when the test is marked as being incomplete.
  • 13.
    PHPUnit – DatabaseExtension PHPUnit Database Extension – DBUnit Port Can be installed by : pear install phpunit/DbUnit Currently supported databases: > MySQL > PostgreSQL > Oracle > SQLite has access to other database systems such as IBM DB2 or Microsoft SQL Server Through Zend Framework or Doctrine 2 integrations
  • 14.
    The four stagesof a database test > Set up fixture > Exercise System Under Test > Verify outcome > Teardown
  • 15.
    Configuration of aPHPUnit Database TestCase Need to Extend abstract TestCase : PHPUnit_Extensions_Database_TestCase require_once 'PHPUnit/Extensions/Database/TestCase.php'; class BankAccountDBTest extends PHPUnit_Extensions_Database_TestCase {
  • 16.
    Configuration of aPHPUnit Database TestCase Must Implement getConnection() - Returns a database connection wrapper. getDataSet() - Returns the dataset to seed the database with.
  • 17.
    Implementation of getConnection()and getDataset() methods <?php require_once 'PHPUnit/Extensions/Database/TestCase.p hp'; class DatabaseTest extends PHPUnit_Extensions_Datab ase_TestCase{ protected function getConnection(){ $pdo = new PDO('mysql:host=localhost;dbname=te stdb', 'root', '');return $this- >createDefaultDBConnection($pdo, 'testdb'); } protected function getDataSet(){return $this- >createFlatXMLDataSet(dirname(__FILE__).'/_files/bank -account-seed.xml'); }}?>
  • 18.
    Test class fordatabase testing //Filename : dbclass.php <?php class BankAccount { public function __construct($accno, $conn, $bal=0) { $this->addData(array($accno,$bal),$conn); }function addData($data, $conn) { $sql = "INSERT INTO bank_account (account_number, balance) VALUES (:acc,:bal)"; $q = $conn->prepare($sql); $q->execute(array(':acc'=>$data[0], ':bal'=>$data[1])); }}
  • 19.
    Test case fordbclass.php <?php require_once 'PHPUnit/Extensions/Database/TestCase.php'; require_once "dbclass.php"; class BankAccountDBTest extends PHPUnit_Extensions_Database_TestCase { protected $pdo; public function __construct() { $this->pdo = new PDO('mysql:host=localhost;dbname=phpunitdb', 'root', 'root'); }
  • 20.
    protected function getConnection() {return $this->createDefaultDBConnection($this->pdo, 'phpunitdb'); } protected function getDataSet(){ return $this- >createFlatXMLDataSet('/var/www/tests/bankaccdb/files/see d.xml'); } public function testaddData(){ $bank_account = new BankAccount('1234567', $this- >pdo); $xml_dataset = $this- >createFlatXMLDataSet('/var/www/tests/bankaccdb/files/see d-after-insert.xml'); $this->assertTablesEqual($xml_dataset- >getTable('bank_account'),$this->getConnection()- >createDataSet()->getTable('bank_account')); }}
  • 21.
    Running the test root@nikunj:/var/www/tests/bankaccdb#phpunit dbclasstest.php PHPUnit 3.6.10 by Sebastian Bergmann. . Time: 0 seconds, Memory: 3.00Mb OK (1 test, 1 assertion)
  • 22.
    Advantages •Testing gives codeauthors and reviewers confidence that patches produce the correct results. •Detect errors just after code is written. •The tests are run at the touch of a button and present their results in a clear format. •Tests run fast. •The tests do not affect each other. If some changes are made in one test, the results of others tests do not change.
  • 23.
    Disadvantages Some people havetrouble with getting started: where to put the files, how big the scope of one unit test is and when to write a separate testing suite and so on. It would be difficult to write a test for people who are not programmers or familiar with PHP.
  • 24.
    Thank You Question. .. .? You can leave comment or Send the message.