SlideShare una empresa de Scribd logo
1 de 39
PHPUnit
Automated Unit Testing Framework.




          By : Varun Taliyan
          OSSCube Solutions Pvt. Ltd.
Unit Test

    Unit : The smallest testable part of an
    application.

    Unit testing : Testing a unit of code
    isolated from its dependencies.

    Testing with PHPUnit : The difference is
    between testing, that is, 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.
PHPUnit

    Part of xUnit family(JUnit, Sunit,...)

    Created by Sebastian Bergmann

    Integrated in most IDE
    
        Eclipse, Netbeans, Zend Stuide, PHPStorm

    Integrated/supported
    
        Zend Studio, Zend Framework, Cake, Symfony
PHPUnit's Goals

    Tests should be:
     
       Easy to learn to write.
     
       Easy to write.
     
       Easy to read.
     
       Easy to execute.
     
       Quick to execute.
     
       Isolated.
     
       Composable.

    Resolve conflicts:
     
       Easy to learn to write versus easy to write.
     
       Isolated versus quick to execute.
Installing PHPUnit

    PHPUnit is installed using the PEAR
    Installer

    Commands to install :
    
        pear config-set auto_discover 1
    
        pear install pear.phpunit.de/PHPUnit
Writing Tests for PHPUnit

    The tests for a class Class go into a class
    ClassTest.

    ClassTest 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.
/Filename : user.php

?php
        Sample PHP class for testing
lass User {

 protected $name;

 public function getName() {

     return $this->name;

 }

 public function setName($name) {

     $this->name = $name;

 }

 public function talk() {

     return "Hello world!";
Test class for testing user.php
?php

equire_once "PHPUnit/Autoload.php";

equire_once "user.php";



lass UserTest extends
PHPUnit_Framework_TestCase
?php
       Test class for testing user.php
..

lass UserTest extends PHPUnit_Framework_TestCase



     // test the talk method

     public function testTalk() {

       // make an instance of the user

       $user = new User();

       // use assertEquals to ensure the greeting is what you expect

       $expected = "Hello world!";

       $actual = $user->talk();

       $this->assertEquals($expected, $actual);
The Command-Line Test Runner

 The PHPUnit command-line test runner
 can be invoked through the phpunit
 command.
phpunit UnitTest UnitTest.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
oot@varuntaliyan:/var/www/test-1# phpunit
userTest.php

HPUnit 3.6.10 by Sebastian Bergmann.




ime: 0 seconds, Memory: 2.75Mb



K (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.
Output when a Test fails
oot@varuntaliyan:/var/www/test-1# phpunit userTest.php




HPUnit 3.6.10 by Sebastian Bergmann.




ime: 0 seconds, Memory: 2.75Mb



here was 1 failure:



) UserTest::testTalk

ailed asserting that two strings are equal.

-- Expected

++ Actual

@ @@

'Hello world!'

'Non sense'



var/www/test-1/userTest.php:14
Test Dependencies
  PHPUnit supports the declaration of explicit dependencies
between test methods. Such dependencies do not define the
order in which the test methods are to be executed but they allow
the returning of an instance of the test fixture by a producer and
passing it to the dependent consumers.



  A producer is a test method that yields its unit under test as
return value.



 A consumer is a test method that depends on one or more
producers and their return values.
lass StackTest extends PHPUnit_Framework_TestCase



 public function testEmpty()

Using the @depends annotation to express dependencies
 {

     $stack = array();

     $this->assertEmpty($stack);

       return $stack;

 }

  /**

  * @depends testEmpty

  */

 public function testPush(array $stack)

 {

     array_push($stack, 'foo');

     $this->assertEquals('foo', $stack[count($stack)-1]);

     $this->assertNotEmpty($stack);

       return $stack;

 }

  /**

  * @depends testPush

  */

 public function testPop(array $stack)

 {
Running the Test
/var/www/test-1# phroot@varuntaliyanpunit depend.php

HPUnit 3.6.10 by Sebastian Bergmann.



..



ime: 0 seconds, Memory: 2.75Mb



K (3 tests, 5 assertions)
Data Providers


test method can accept arbitrary
argumeants. These arguments are to
be provided by a data provider
methods.
lass DataTest extends PHPUnit_Framework_TestCase


Using a data provider that returns an array of arrays
/**

  * @dataProvider provider

  */

 public function testAdd($a, $b, $c)

 {

     $this->assertEquals($c, $a + $b);

 }

  public function provider()

 {

     return array(

       array(0, 0, 0),

       array(0, 1, 1),

       array(1, 0, 1),

       array(1, 1, 3)
Testing Exceptions : Tests whether an exception is
/Filename : exceptionclass.php

?php
thrown inside the tested code.
ni_set('display_errors', 1);

lass myexcepclass extends Exception {

unction checkNum($number)

{

if($number>1)

    {

    throw new Exception("Value must be 1 or below");

    }

return true;
?php
Test class for exceptionclass.php
equire_once '/usr/share/php/PHPUnit/Framework/TestCase.php';

equire_once 'exceptionclass.php';

lass myexcepclassTest extends PHPUnit_Framework_TestCase {

**

* @expectedException InvalidArgumentException:

*/

public function testcheckNum() {

     $obj = new MyCustomException;

     $obj->checkNum(2);

}
Running the test
HPUnit 3.6.10 by Sebasroot@varuntaliyan:/var/www/tests/error# phpunit
testexceptionclass.php

ian Bergmann.



ime: 0 seconds, Memory: 2.75Mb



here was 1 failure:



) myexcepclassTest::testcheckNum

ailed asserting that exception of type "Exception" matches expected exception
"InvalidArgumentException:".




AILURES!
Testing Output :            Sometimes you want to assert that the
execution of a method, for instance, generates an expected
/Filename : outputclass.php

output
?php

ni_set('display_errors', 1);

lass Myoutputclass {

unction greetings()

{

print 'Hello Everyone';

}

unction quote()

{

print 'Its morning again';

}
/Filename : testoutputclass.php

?php


  Test class for outputclass.php
equire_once '/usr/share/php/PHPUnit/Framework/TestCase.php';

equire_once 'outputclass.php';



lass outputclassTest extends PHPUnit_Framework_TestCase



 protected $obj;



 protected function setUp() {

 $this->obj = new Myoutputclass;

 }



 public function testgreetings()

 {

$this->expectOutputString('Hello Everyone');



$this->obj->greetings();



 }



 public function testquote()

 {

$this->expectOutputString('Its noon');



$this->obj->quote();
Running the test
oot@varuntaliyan:/var/www/tests/output# phpunit testoutputclass.php

HPUnit 3.6.10 by Sebastian Bergmann.



F



ime: 0 seconds, Memory: 2.75Mb



here was 1 failure:



) outputclassTest::testquote

ailed asserting that two strings are equal.

-- Expected

++ Actual

@ @@

'Its noon'

'Its morning again'




AILURES!
Assertions

    assertArrayHasKey()

    assertContains()

    assertContainsOnly()

    assertCount()

    assertEmpty()

    assertEquals()

    assertFalse()

    assertClassHasAttribute()

    assertClassHasStaticAttribute().....

    assertGreaterThan()

    assertGreaterThanOrEqual()

    assertInstanceOf()

    assertInternalType()

    assertLessThan()

    assertLessThanOrEqual()

    assertNull()

    assertRegExp()

    assertSame()

    assertStringEndsWith()

    assertStringStartsWith()......
Fixtures

    is a “known state” of an application

    need to be “set up” at the start of test

    need to be “torn down” at the end of the
    test

    shares “states” over test methods

    setUp() is where you create the objects
    against which you will test.

    tearDown() is where you clean up the
    objects against which you tested.

    More setUp() than tearDown()
Using setUp() to create the stack fixture
<?php
class StackTest extends PHPUnit_Framework_TestCase
{
   protected $stack;
    protected function setUp()
   {
     $this->stack = array();
   }
    public function testEmpty()
   {
     $this->assertTrue(empty($this->stack));
   }
    public function testPush()
   {
     array_push($this->stack, 'foo');
     $this->assertEquals('foo', $this->stack[count($this->stack)-1]);
     $this->assertFalse(empty($this->stack));
   }

  public function testPop()
  {
    array_push($this->stack, 'foo');
    $this->assertEquals('foo', array_pop($this->stack));
    $this->assertTrue(empty($this->stack));
  }
}
?>
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

    1.Set up fixture
    2.Exercise System Under Test
    3.Verify outcome
    4.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.php';

 class DatabaseTest extends PHPUnit_Extensions_Database_TestCase
 {
    protected function getConnection()
    {
      $pdo = new PDO('mysql:host=localhost;dbname=testdb', '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

lass BankAccount {

ublic function __construct($accno, $conn, $bal=0) {

this->addData(array($accno,$bal),$conn);



unction addData($data, $conn) {

sql = "INSERT INTO bank_account (account_number, balance) VALUES (:acc,:bal)";

q = $conn->prepare($sql);

q->execute(array(':acc'=>$data[0],
Test case for dbclass.php
?php

equire_once 'PHPUnit/Extensions/Database/TestCase.php';

equire_once "dbclass.php";

lass 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/seed.xml');

 }

 public function testaddData()
Running the test

oot@varuntaliyan:/var/www/tests/bank
accdb# phpunit dbclasstest.php

HPUnit 3.6.10 by Sebastian Bergmann.



ime: 0 seconds, Memory: 3.00Mb
Output when a Test fails
oot@varuntaliyan:/var/www/tests/bankaccdb# phpunit dbclasstest.php

HPUnit 3.6.10 by Sebastian Bergmann.



ime: 0 seconds, Memory: 3.00Mb

here was 1 failure:

) BankAccountDBTest::testaddData

ailed asserting that

----------------------+----------------------+

bank_account                             |

----------------------+----------------------+

  account_number |                balance        |

----------------------+----------------------+

     1593490          |       100         |

----------------------+----------------------+

     1593648          |       1216        |
+----------------------+----------------------+

| bank_account                                        |

+----------------------+----------------------+

| account_number |            balance             |

+----------------------+----------------------+

|     1593490           |      100.00         |

+----------------------+----------------------+

|     1593648           |     1216.00         |

+----------------------+----------------------+

|     1234861           |      89.00          |

+----------------------+----------------------+

|     1593648           |     1216.00         |

+----------------------+----------------------+

/var/www/tests/bankaccdb/dbclasstest.php:29



FAILURES!

Tests: 1, Assertions: 1, Failures: 1.
Thank you - Resources

    http://
    www.phpunit.de/manual/3.6/en/index.html

    http://www.ds-o.com/archives/63-
    PHPUnit-Database-Extension-DBUnit-
    Port.html

Más contenido relacionado

La actualidad más candente

Advanced PHPUnit Testing
Advanced PHPUnit TestingAdvanced PHPUnit Testing
Advanced PHPUnit TestingMike Lively
 
Unit testing with PHPUnit - there's life outside of TDD
Unit testing with PHPUnit - there's life outside of TDDUnit testing with PHPUnit - there's life outside of TDD
Unit testing with PHPUnit - there's life outside of TDDPaweł Michalik
 
Unit testing PHP apps with PHPUnit
Unit testing PHP apps with PHPUnitUnit testing PHP apps with PHPUnit
Unit testing PHP apps with PHPUnitMichelangelo van Dam
 
Mocking Dependencies in PHPUnit
Mocking Dependencies in PHPUnitMocking Dependencies in PHPUnit
Mocking Dependencies in PHPUnitmfrost503
 
Beginning PHPUnit
Beginning PHPUnitBeginning PHPUnit
Beginning PHPUnitJace Ju
 
Unit Testng with PHP Unit - A Step by Step Training
Unit Testng with PHP Unit - A Step by Step TrainingUnit Testng with PHP Unit - A Step by Step Training
Unit Testng with PHP Unit - A Step by Step TrainingRam Awadh Prasad, PMP
 
Unlock The Mystery Of PHPUnit (Wave PHP 2018)
Unlock The Mystery Of PHPUnit (Wave PHP 2018)Unlock The Mystery Of PHPUnit (Wave PHP 2018)
Unlock The Mystery Of PHPUnit (Wave PHP 2018)ENDelt260
 
Building Testable PHP Applications
Building Testable PHP ApplicationsBuilding Testable PHP Applications
Building Testable PHP Applicationschartjes
 
Test Driven Development With Python
Test Driven Development With PythonTest Driven Development With Python
Test Driven Development With PythonSiddhi
 
EPHPC Webinar Slides: Unit Testing by Arthur Purnama
EPHPC Webinar Slides: Unit Testing by Arthur PurnamaEPHPC Webinar Slides: Unit Testing by Arthur Purnama
EPHPC Webinar Slides: Unit Testing by Arthur PurnamaEnterprise PHP Center
 
Effective testing with pytest
Effective testing with pytestEffective testing with pytest
Effective testing with pytestHector Canto
 
Python Unit Test
Python Unit TestPython Unit Test
Python Unit TestDavid Xie
 
Testing Code and Assuring Quality
Testing Code and Assuring QualityTesting Code and Assuring Quality
Testing Code and Assuring QualityKent Cowgill
 
Test in action week 2
Test in action   week 2Test in action   week 2
Test in action week 2Yi-Huan Chan
 
Python testing using mock and pytest
Python testing using mock and pytestPython testing using mock and pytest
Python testing using mock and pytestSuraj Deshmukh
 
Testes pythonicos com pytest
Testes pythonicos com pytestTestes pythonicos com pytest
Testes pythonicos com pytestviniciusban
 

La actualidad más candente (20)

Advanced PHPUnit Testing
Advanced PHPUnit TestingAdvanced PHPUnit Testing
Advanced PHPUnit Testing
 
Unit testing with PHPUnit - there's life outside of TDD
Unit testing with PHPUnit - there's life outside of TDDUnit testing with PHPUnit - there's life outside of TDD
Unit testing with PHPUnit - there's life outside of TDD
 
Phpunit testing
Phpunit testingPhpunit testing
Phpunit testing
 
PHPUnit
PHPUnitPHPUnit
PHPUnit
 
Unit testing PHP apps with PHPUnit
Unit testing PHP apps with PHPUnitUnit testing PHP apps with PHPUnit
Unit testing PHP apps with PHPUnit
 
Mocking Dependencies in PHPUnit
Mocking Dependencies in PHPUnitMocking Dependencies in PHPUnit
Mocking Dependencies in PHPUnit
 
Beginning PHPUnit
Beginning PHPUnitBeginning PHPUnit
Beginning PHPUnit
 
Unit Testng with PHP Unit - A Step by Step Training
Unit Testng with PHP Unit - A Step by Step TrainingUnit Testng with PHP Unit - A Step by Step Training
Unit Testng with PHP Unit - A Step by Step Training
 
Unlock The Mystery Of PHPUnit (Wave PHP 2018)
Unlock The Mystery Of PHPUnit (Wave PHP 2018)Unlock The Mystery Of PHPUnit (Wave PHP 2018)
Unlock The Mystery Of PHPUnit (Wave PHP 2018)
 
Building Testable PHP Applications
Building Testable PHP ApplicationsBuilding Testable PHP Applications
Building Testable PHP Applications
 
Unit testing
Unit testingUnit testing
Unit testing
 
Test Driven Development With Python
Test Driven Development With PythonTest Driven Development With Python
Test Driven Development With Python
 
EPHPC Webinar Slides: Unit Testing by Arthur Purnama
EPHPC Webinar Slides: Unit Testing by Arthur PurnamaEPHPC Webinar Slides: Unit Testing by Arthur Purnama
EPHPC Webinar Slides: Unit Testing by Arthur Purnama
 
Effective testing with pytest
Effective testing with pytestEffective testing with pytest
Effective testing with pytest
 
PHPUnit testing to Zend_Test
PHPUnit testing to Zend_TestPHPUnit testing to Zend_Test
PHPUnit testing to Zend_Test
 
Python Unit Test
Python Unit TestPython Unit Test
Python Unit Test
 
Testing Code and Assuring Quality
Testing Code and Assuring QualityTesting Code and Assuring Quality
Testing Code and Assuring Quality
 
Test in action week 2
Test in action   week 2Test in action   week 2
Test in action week 2
 
Python testing using mock and pytest
Python testing using mock and pytestPython testing using mock and pytest
Python testing using mock and pytest
 
Testes pythonicos com pytest
Testes pythonicos com pytestTestes pythonicos com pytest
Testes pythonicos com pytest
 

Destacado

IPC 2013 - High Performance PHP with HipHop
IPC 2013 - High Performance PHP with HipHopIPC 2013 - High Performance PHP with HipHop
IPC 2013 - High Performance PHP with HipHopSteve Kamerman
 
PHP Unit y TDD
PHP Unit y TDDPHP Unit y TDD
PHP Unit y TDDEmergya
 
Automated php unit testing in drupal 8
Automated php unit testing in drupal 8Automated php unit testing in drupal 8
Automated php unit testing in drupal 8Jay Friendly
 
PHPUnit with CakePHP and Yii
PHPUnit with CakePHP and YiiPHPUnit with CakePHP and Yii
PHPUnit with CakePHP and Yiimadhavi Ghadge
 
Automated Testing in WordPress, Really?!
Automated Testing in WordPress, Really?!Automated Testing in WordPress, Really?!
Automated Testing in WordPress, Really?!Ptah Dunbar
 
PhpUnit - The most unknown Parts
PhpUnit - The most unknown PartsPhpUnit - The most unknown Parts
PhpUnit - The most unknown PartsBastian Feder
 
Unit Testing in PHP
Unit Testing in PHPUnit Testing in PHP
Unit Testing in PHPRadu Murzea
 
Chapter 8 kotler quiz slideshare
Chapter 8 kotler quiz slideshareChapter 8 kotler quiz slideshare
Chapter 8 kotler quiz slidesharerebs andal
 
Sarah's Intro Presentation
Sarah's Intro PresentationSarah's Intro Presentation
Sarah's Intro Presentationsarahashleyoso
 
Tapping into Employees Wisdom by Scott Wilder
Tapping into Employees Wisdom by Scott WilderTapping into Employees Wisdom by Scott Wilder
Tapping into Employees Wisdom by Scott WilderEdelman Digital
 
I G W U B O R M E R C Y I F E O M A
I G W U B O R  M E R C Y  I F E O M AI G W U B O R  M E R C Y  I F E O M A
I G W U B O R M E R C Y I F E O M Aguest884642
 
Personal decription
Personal decriptionPersonal decription
Personal decriptiongabriela
 
36氪《氪周刊》Vol.55
36氪《氪周刊》Vol.5536氪《氪周刊》Vol.55
36氪《氪周刊》Vol.55Chada Chiu
 
Presentation To Avvo Conference 011910 Re Linkedin
Presentation To Avvo Conference 011910 Re LinkedinPresentation To Avvo Conference 011910 Re Linkedin
Presentation To Avvo Conference 011910 Re LinkedinDoug Mandell
 

Destacado (20)

to Test or not to Test?
to Test or not to Test?to Test or not to Test?
to Test or not to Test?
 
Test Driven Development
Test Driven DevelopmentTest Driven Development
Test Driven Development
 
chapters
chapterschapters
chapters
 
IPC 2013 - High Performance PHP with HipHop
IPC 2013 - High Performance PHP with HipHopIPC 2013 - High Performance PHP with HipHop
IPC 2013 - High Performance PHP with HipHop
 
PHP Unit y TDD
PHP Unit y TDDPHP Unit y TDD
PHP Unit y TDD
 
Automated php unit testing in drupal 8
Automated php unit testing in drupal 8Automated php unit testing in drupal 8
Automated php unit testing in drupal 8
 
PHPUnit with CakePHP and Yii
PHPUnit with CakePHP and YiiPHPUnit with CakePHP and Yii
PHPUnit with CakePHP and Yii
 
Automated Testing in WordPress, Really?!
Automated Testing in WordPress, Really?!Automated Testing in WordPress, Really?!
Automated Testing in WordPress, Really?!
 
PhpUnit - The most unknown Parts
PhpUnit - The most unknown PartsPhpUnit - The most unknown Parts
PhpUnit - The most unknown Parts
 
Unit Testing in PHP
Unit Testing in PHPUnit Testing in PHP
Unit Testing in PHP
 
Chapter 8 kotler quiz slideshare
Chapter 8 kotler quiz slideshareChapter 8 kotler quiz slideshare
Chapter 8 kotler quiz slideshare
 
Evaluation
EvaluationEvaluation
Evaluation
 
Sarah's Intro Presentation
Sarah's Intro PresentationSarah's Intro Presentation
Sarah's Intro Presentation
 
Tapping into Employees Wisdom by Scott Wilder
Tapping into Employees Wisdom by Scott WilderTapping into Employees Wisdom by Scott Wilder
Tapping into Employees Wisdom by Scott Wilder
 
I G W U B O R M E R C Y I F E O M A
I G W U B O R  M E R C Y  I F E O M AI G W U B O R  M E R C Y  I F E O M A
I G W U B O R M E R C Y I F E O M A
 
Personal decription
Personal decriptionPersonal decription
Personal decription
 
36氪《氪周刊》Vol.55
36氪《氪周刊》Vol.5536氪《氪周刊》Vol.55
36氪《氪周刊》Vol.55
 
Erik Johannson
Erik JohannsonErik Johannson
Erik Johannson
 
Presentation To Avvo Conference 011910 Re Linkedin
Presentation To Avvo Conference 011910 Re LinkedinPresentation To Avvo Conference 011910 Re Linkedin
Presentation To Avvo Conference 011910 Re Linkedin
 
My Family & Me
My Family & MeMy Family & Me
My Family & Me
 

Similar a Unit Testing using PHPUnit

Fighting Fear-Driven-Development With PHPUnit
Fighting Fear-Driven-Development With PHPUnitFighting Fear-Driven-Development With PHPUnit
Fighting Fear-Driven-Development With PHPUnitJames Fuller
 
Automated Unit Testing
Automated Unit TestingAutomated Unit Testing
Automated Unit TestingMike Lively
 
Php Unit With Zend Framework Zendcon09
Php Unit With Zend Framework   Zendcon09Php Unit With Zend Framework   Zendcon09
Php Unit With Zend Framework Zendcon09Michelangelo van Dam
 
Php unit the-mostunknownparts
Php unit the-mostunknownpartsPhp unit the-mostunknownparts
Php unit the-mostunknownpartsBastian Feder
 
international PHP2011_Bastian Feder_The most unknown Parts of PHPUnit
international PHP2011_Bastian Feder_The most unknown Parts of PHPUnitinternational PHP2011_Bastian Feder_The most unknown Parts of PHPUnit
international PHP2011_Bastian Feder_The most unknown Parts of PHPUnitsmueller_sandsmedia
 
Writing Test Cases with PHPUnit
Writing Test Cases with PHPUnitWriting Test Cases with PHPUnit
Writing Test Cases with PHPUnitShouvik Chatterjee
 
PHPunit and you
PHPunit and youPHPunit and you
PHPunit and youmarkstory
 
Unit testing for WordPress
Unit testing for WordPressUnit testing for WordPress
Unit testing for WordPressHarshad Mane
 
MT_01_unittest_python.pdf
MT_01_unittest_python.pdfMT_01_unittest_python.pdf
MT_01_unittest_python.pdfHans Jones
 
Unit testing php-unit - phing - selenium_v2
Unit testing   php-unit - phing - selenium_v2Unit testing   php-unit - phing - selenium_v2
Unit testing php-unit - phing - selenium_v2Tricode (part of Dept)
 
13 PHPUnit #burningkeyboards
13 PHPUnit #burningkeyboards13 PHPUnit #burningkeyboards
13 PHPUnit #burningkeyboardsDenis Ristic
 
Php session 3 Important topics
Php session 3 Important topicsPhp session 3 Important topics
Php session 3 Important topicsSpy Seat
 
Php unit the-mostunknownparts
Php unit the-mostunknownpartsPhp unit the-mostunknownparts
Php unit the-mostunknownpartsBastian Feder
 

Similar a Unit Testing using PHPUnit (20)

Fighting Fear-Driven-Development With PHPUnit
Fighting Fear-Driven-Development With PHPUnitFighting Fear-Driven-Development With PHPUnit
Fighting Fear-Driven-Development With PHPUnit
 
Automated Unit Testing
Automated Unit TestingAutomated Unit Testing
Automated Unit Testing
 
Phpunit
PhpunitPhpunit
Phpunit
 
Php Unit With Zend Framework Zendcon09
Php Unit With Zend Framework   Zendcon09Php Unit With Zend Framework   Zendcon09
Php Unit With Zend Framework Zendcon09
 
Php unit the-mostunknownparts
Php unit the-mostunknownpartsPhp unit the-mostunknownparts
Php unit the-mostunknownparts
 
international PHP2011_Bastian Feder_The most unknown Parts of PHPUnit
international PHP2011_Bastian Feder_The most unknown Parts of PHPUnitinternational PHP2011_Bastian Feder_The most unknown Parts of PHPUnit
international PHP2011_Bastian Feder_The most unknown Parts of PHPUnit
 
Writing Test Cases with PHPUnit
Writing Test Cases with PHPUnitWriting Test Cases with PHPUnit
Writing Test Cases with PHPUnit
 
3 j unit
3 j unit3 j unit
3 j unit
 
Laravel Unit Testing
Laravel Unit TestingLaravel Unit Testing
Laravel Unit Testing
 
PHPunit and you
PHPunit and youPHPunit and you
PHPunit and you
 
Unit testing for WordPress
Unit testing for WordPressUnit testing for WordPress
Unit testing for WordPress
 
MT_01_unittest_python.pdf
MT_01_unittest_python.pdfMT_01_unittest_python.pdf
MT_01_unittest_python.pdf
 
Unit testing
Unit testingUnit testing
Unit testing
 
Php unit (eng)
Php unit (eng)Php unit (eng)
Php unit (eng)
 
Junit_.pptx
Junit_.pptxJunit_.pptx
Junit_.pptx
 
Unit testing php-unit - phing - selenium_v2
Unit testing   php-unit - phing - selenium_v2Unit testing   php-unit - phing - selenium_v2
Unit testing php-unit - phing - selenium_v2
 
13 PHPUnit #burningkeyboards
13 PHPUnit #burningkeyboards13 PHPUnit #burningkeyboards
13 PHPUnit #burningkeyboards
 
Php tests tips
Php tests tipsPhp tests tips
Php tests tips
 
Php session 3 Important topics
Php session 3 Important topicsPhp session 3 Important topics
Php session 3 Important topics
 
Php unit the-mostunknownparts
Php unit the-mostunknownpartsPhp unit the-mostunknownparts
Php unit the-mostunknownparts
 

Último

A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024Results
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilV3cube
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...gurkirankumar98700
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Paola De la Torre
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 

Último (20)

A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of Brazil
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 

Unit Testing using PHPUnit

  • 1. PHPUnit Automated Unit Testing Framework. By : Varun Taliyan OSSCube Solutions Pvt. Ltd.
  • 2. Unit Test  Unit : The smallest testable part of an application.  Unit testing : Testing a unit of code isolated from its dependencies.  Testing with PHPUnit : The difference is between testing, that is, 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.
  • 3. PHPUnit  Part of xUnit family(JUnit, Sunit,...)  Created by Sebastian Bergmann  Integrated in most IDE  Eclipse, Netbeans, Zend Stuide, PHPStorm  Integrated/supported  Zend Studio, Zend Framework, Cake, Symfony
  • 4. PHPUnit's Goals  Tests should be:  Easy to learn to write.  Easy to write.  Easy to read.  Easy to execute.  Quick to execute.  Isolated.  Composable.  Resolve conflicts:  Easy to learn to write versus easy to write.  Isolated versus quick to execute.
  • 5. Installing PHPUnit  PHPUnit is installed using the PEAR Installer  Commands to install :  pear config-set auto_discover 1  pear install pear.phpunit.de/PHPUnit
  • 6. Writing Tests for PHPUnit  The tests for a class Class go into a class ClassTest.  ClassTest 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. /Filename : user.php ?php Sample PHP class for testing lass User { protected $name; public function getName() { return $this->name; } public function setName($name) { $this->name = $name; } public function talk() { return "Hello world!";
  • 8. Test class for testing user.php ?php equire_once "PHPUnit/Autoload.php"; equire_once "user.php"; lass UserTest extends PHPUnit_Framework_TestCase
  • 9. ?php Test class for testing user.php .. lass UserTest extends PHPUnit_Framework_TestCase // test the talk method public function testTalk() { // make an instance of the user $user = new User(); // use assertEquals to ensure the greeting is what you expect $expected = "Hello world!"; $actual = $user->talk(); $this->assertEquals($expected, $actual);
  • 10. The Command-Line Test Runner  The PHPUnit command-line test runner can be invoked through the phpunit command. phpunit UnitTest UnitTest.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 oot@varuntaliyan:/var/www/test-1# phpunit userTest.php HPUnit 3.6.10 by Sebastian Bergmann. ime: 0 seconds, Memory: 2.75Mb K (1 test, 1 assertion)
  • 12. 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.
  • 13. Output when a Test fails oot@varuntaliyan:/var/www/test-1# phpunit userTest.php HPUnit 3.6.10 by Sebastian Bergmann. ime: 0 seconds, Memory: 2.75Mb here was 1 failure: ) UserTest::testTalk ailed asserting that two strings are equal. -- Expected ++ Actual @ @@ 'Hello world!' 'Non sense' var/www/test-1/userTest.php:14
  • 14. Test Dependencies PHPUnit supports the declaration of explicit dependencies between test methods. Such dependencies do not define the order in which the test methods are to be executed but they allow the returning of an instance of the test fixture by a producer and passing it to the dependent consumers. A producer is a test method that yields its unit under test as return value. A consumer is a test method that depends on one or more producers and their return values.
  • 15. lass StackTest extends PHPUnit_Framework_TestCase public function testEmpty() Using the @depends annotation to express dependencies { $stack = array(); $this->assertEmpty($stack); return $stack; } /** * @depends testEmpty */ public function testPush(array $stack) { array_push($stack, 'foo'); $this->assertEquals('foo', $stack[count($stack)-1]); $this->assertNotEmpty($stack); return $stack; } /** * @depends testPush */ public function testPop(array $stack) {
  • 16. Running the Test /var/www/test-1# phroot@varuntaliyanpunit depend.php HPUnit 3.6.10 by Sebastian Bergmann. .. ime: 0 seconds, Memory: 2.75Mb K (3 tests, 5 assertions)
  • 17. Data Providers test method can accept arbitrary argumeants. These arguments are to be provided by a data provider methods.
  • 18. lass DataTest extends PHPUnit_Framework_TestCase Using a data provider that returns an array of arrays /** * @dataProvider provider */ public function testAdd($a, $b, $c) { $this->assertEquals($c, $a + $b); } public function provider() { return array( array(0, 0, 0), array(0, 1, 1), array(1, 0, 1), array(1, 1, 3)
  • 19. Testing Exceptions : Tests whether an exception is /Filename : exceptionclass.php ?php thrown inside the tested code. ni_set('display_errors', 1); lass myexcepclass extends Exception { unction checkNum($number) { if($number>1) { throw new Exception("Value must be 1 or below"); } return true;
  • 20. ?php Test class for exceptionclass.php equire_once '/usr/share/php/PHPUnit/Framework/TestCase.php'; equire_once 'exceptionclass.php'; lass myexcepclassTest extends PHPUnit_Framework_TestCase { ** * @expectedException InvalidArgumentException: */ public function testcheckNum() { $obj = new MyCustomException; $obj->checkNum(2); }
  • 21. Running the test HPUnit 3.6.10 by Sebasroot@varuntaliyan:/var/www/tests/error# phpunit testexceptionclass.php ian Bergmann. ime: 0 seconds, Memory: 2.75Mb here was 1 failure: ) myexcepclassTest::testcheckNum ailed asserting that exception of type "Exception" matches expected exception "InvalidArgumentException:". AILURES!
  • 22. Testing Output : Sometimes you want to assert that the execution of a method, for instance, generates an expected /Filename : outputclass.php output ?php ni_set('display_errors', 1); lass Myoutputclass { unction greetings() { print 'Hello Everyone'; } unction quote() { print 'Its morning again'; }
  • 23. /Filename : testoutputclass.php ?php Test class for outputclass.php equire_once '/usr/share/php/PHPUnit/Framework/TestCase.php'; equire_once 'outputclass.php'; lass outputclassTest extends PHPUnit_Framework_TestCase protected $obj; protected function setUp() { $this->obj = new Myoutputclass; } public function testgreetings() { $this->expectOutputString('Hello Everyone'); $this->obj->greetings(); } public function testquote() { $this->expectOutputString('Its noon'); $this->obj->quote();
  • 24. Running the test oot@varuntaliyan:/var/www/tests/output# phpunit testoutputclass.php HPUnit 3.6.10 by Sebastian Bergmann. F ime: 0 seconds, Memory: 2.75Mb here was 1 failure: ) outputclassTest::testquote ailed asserting that two strings are equal. -- Expected ++ Actual @ @@ 'Its noon' 'Its morning again' AILURES!
  • 25. Assertions  assertArrayHasKey()  assertContains()  assertContainsOnly()  assertCount()  assertEmpty()  assertEquals()  assertFalse()  assertClassHasAttribute()  assertClassHasStaticAttribute().....
  • 26. assertGreaterThan()  assertGreaterThanOrEqual()  assertInstanceOf()  assertInternalType()  assertLessThan()  assertLessThanOrEqual()  assertNull()  assertRegExp()  assertSame()  assertStringEndsWith()  assertStringStartsWith()......
  • 27. Fixtures  is a “known state” of an application  need to be “set up” at the start of test  need to be “torn down” at the end of the test  shares “states” over test methods  setUp() is where you create the objects against which you will test.  tearDown() is where you clean up the objects against which you tested.  More setUp() than tearDown()
  • 28. Using setUp() to create the stack fixture <?php class StackTest extends PHPUnit_Framework_TestCase { protected $stack; protected function setUp() { $this->stack = array(); } public function testEmpty() { $this->assertTrue(empty($this->stack)); } public function testPush() { array_push($this->stack, 'foo'); $this->assertEquals('foo', $this->stack[count($this->stack)-1]); $this->assertFalse(empty($this->stack)); } public function testPop() { array_push($this->stack, 'foo'); $this->assertEquals('foo', array_pop($this->stack)); $this->assertTrue(empty($this->stack)); } } ?>
  • 29. 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
  • 30. The four stages of a database test 1.Set up fixture 2.Exercise System Under Test 3.Verify outcome 4.Teardown
  • 31. 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 { }
  • 32. Configuration of a PHPUnit Database TestCase  Must Implement getConnection() - Returns a database connection wrapper. getDataSet() - Returns the dataset to seed the database with.
  • 33. Implementation of getConnection() and getDataset() methods ?php require_once 'PHPUnit/Extensions/Database/TestCase.php'; class DatabaseTest extends PHPUnit_Extensions_Database_TestCase { protected function getConnection() { $pdo = new PDO('mysql:host=localhost;dbname=testdb', 'root', ''); return $this->createDefaultDBConnection($pdo, 'testdb'); } protected function getDataSet() { return $this->createFlatXMLDataSet(dirname(__FILE__).'/_files/bank- account-seed.xml'); } } ?>
  • 34. Test class for database testing /Filename : dbclass.php ?php lass BankAccount { ublic function __construct($accno, $conn, $bal=0) { this->addData(array($accno,$bal),$conn); unction addData($data, $conn) { sql = "INSERT INTO bank_account (account_number, balance) VALUES (:acc,:bal)"; q = $conn->prepare($sql); q->execute(array(':acc'=>$data[0],
  • 35. Test case for dbclass.php ?php equire_once 'PHPUnit/Extensions/Database/TestCase.php'; equire_once "dbclass.php"; lass 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/seed.xml'); } public function testaddData()
  • 36. Running the test oot@varuntaliyan:/var/www/tests/bank accdb# phpunit dbclasstest.php HPUnit 3.6.10 by Sebastian Bergmann. ime: 0 seconds, Memory: 3.00Mb
  • 37. Output when a Test fails oot@varuntaliyan:/var/www/tests/bankaccdb# phpunit dbclasstest.php HPUnit 3.6.10 by Sebastian Bergmann. ime: 0 seconds, Memory: 3.00Mb here was 1 failure: ) BankAccountDBTest::testaddData ailed asserting that ----------------------+----------------------+ bank_account | ----------------------+----------------------+ account_number | balance | ----------------------+----------------------+ 1593490 | 100 | ----------------------+----------------------+ 1593648 | 1216 |
  • 38. +----------------------+----------------------+ | bank_account | +----------------------+----------------------+ | account_number | balance | +----------------------+----------------------+ | 1593490 | 100.00 | +----------------------+----------------------+ | 1593648 | 1216.00 | +----------------------+----------------------+ | 1234861 | 89.00 | +----------------------+----------------------+ | 1593648 | 1216.00 | +----------------------+----------------------+ /var/www/tests/bankaccdb/dbclasstest.php:29 FAILURES! Tests: 1, Assertions: 1, Failures: 1.
  • 39. Thank you - Resources  http:// www.phpunit.de/manual/3.6/en/index.html  http://www.ds-o.com/archives/63- PHPUnit-Database-Extension-DBUnit- Port.html