SlideShare a Scribd company logo
The most unknown parts of
PHPUnit




Bastian Feder         IPC Spring 2011 Berlinl
lapistano@php.net              1st June 2011
Me, myself & I

 JavaScript since 2002
 PHP since 2001
 Trainer & coach
 Opensource addict
   PHP manual translations
   FluentDOM
   ...
CLI
… on the command line

 -- testdox[-(html|text)]         -- filter <pattern>
 generates a especially styled    filters which testsuite to run.
 test report.

     $ phpunit --filter Handler --testdox ./
     PHPUnit 3.4.15 by Sebastian Bergmann.

     FluentDOMCore
      [x] Get handler

     FluentDOMHandler
      [x] Insert nodes after
      [x] Insert nodes before
… on the command line                            (cont.)



 -- strict
 marks test without an assertion as incomplete. Use in
 combination with –verbose to get the name of the test.
 -- coverage-(html|source|clover) <(dir|file)>
 generates a report on how many lines of the code has how often
 been executed.
 -- group <groupname [, groupname]>
 runs only the named group(s).
 -- d key[=value]
 alter ini-settings (e.g. memory_limit, max_execution_time)
Annotations
Annotations

 „In software programming, annotations are used
 mainly for the purpose of expanding code
 documentation and comments. They are typically
 ignored when the code is compiled or executed.“
 ( Wikipedia: http://en.wikipedia.org/w/index.php?title=Annotation&oldid=385076084 )
Annotations              (cont.)



/** @covers, @group
 * @covers myClass::run
 * @group exceptions
 * @group Trac-123
 */
public function testInvalidArgumentException() {

     $obj = new myClass();
     try{
         $obj->run( 'invalidArgument' );
         $this->fail('Expected exception not thrown.');
     } catch ( InvalidArgumentException $e ) {
     }
}
Annotations              (cont.)



    Depending on other tests

public function testIsApcAvailable() {

     if ( ! extension_loaded( 'apc' ) ) {
         $this->markTestSkipped( 'Required APC not available' );
     }
}

/**
 * @depend testIsApcAvailable
 */
public function testGetFileFromAPC () {

}
Assertions
Assertions

 „In computer programming, an assertion is a predicate
 (for example a true–false statement) placed in a
 program to indicate that the developer thinks that the
 predicate is always true at that place. [...]
 It may be used to verify that an assumption made by
 the programmer during the implementation of the
 program remains valid when the program is executed..
 [...]“

 (Wikipedia, http://en.wikipedia.org/w/index.php?title=Assertion_(computing)&oldid=382473744)
Assertions          (cont.)



 assertContains(), assertContainsOnly()

 Cameleon within the asserts, handles
    Strings ( like strpos() )
    Arrays ( like in_array() )

$this->assertContains('bar', 'foobar');                    // ✓

$this->assertContainsOnly('string', array('1', '2', 3));   // ✗
Assertions         (cont.)



 assertXMLFileEqualsXMLFile()
 assertXMLStringEqualsXMLFile()
 assertXMLStringEqualsXMLString()

 $this->assertXMLFileEqualsXMLFile(
     '/path/to/Expected.xml',
     '/path/to/Fixture.xml'
 );
Assertions      (cont.)


     $ phpunit XmlFileEqualsXmlFileTest.php
     PHPUnit 3.4.15 by Sebastian Bergmann.
     …

     1) XmlFileEqualsXmlFileTest::testFailure
     Failed asserting that two strings are
     equal.
     --- Expected
     +++ Actual
     @@ -1,4 +1,4 @@
      <?xml version="1.0"?>
      <foo>
     - <bar/>
     + <baz/>
      </foo>

     /dev/tests/XmlFileEqualsXmlFileTest.php:7
Assertions           (cont.)


 assertAttribute*()

 Asserts the content of a class attribute regardless its
 visibility
 […]
       private $collection = array( 1, 2, '3' );
       private $name = 'Jakob';
 […]

 $this->assertAttributeContainsOnly(
     'integer', 'collection', new myClass );

 $this->assertAttributeContains(
     'ko', 'name', new myClass );
Assertions         (cont.)



 assertType()
 // TYPE_OBJECT
 $this->assertType( 'FluentDOM', new FluentDOM );

 $this->assertInstanceOf( 'FluentDOM', new FluentDOM );

 // TYPE_STRING
 $this->assertInternalType( 'string', '4221' );

 // TYPE_INTEGER
 $this->assertInternalType( 'integer', 4221 );

 // TYPE_RESSOURCE
 $this->assertInternalType(
     'resource', fopen('/file.txt', 'r' );
Assertions         (cont.)



 assertSelectRegExp()
 $xml = '
      <items version="1.0">
        <persons>
          <person class="firstname">Thomas</person>
          <person class="firstname">Jakob</person>
          <person class="firstname">Bastian</person>
        </persons>
      </items>
   ';

 $this->assertSelectRegExp(
     'person[class*="name"]','(Jakob|Bastian)', 2, $xml);
Assertions         (cont.)



 assertThat()

 Evaluates constraints to build complex assertions.
 $this->assertThat(
     $expected,
     $ths->logicalAnd(
         $this->isInstanceOf('tire'),
         $this->logicalNot(
             $this->identicalTo($myFrontTire)
         )
     )
 );
Weaving in
Test Listeners

 Get called on several states of the test runner
   startTest
   endTest
   addIncompleteTest
   …
Test Listeners            (cont.)



 Configuration
   Add to your phpunit.xml
 <listeners>
   <listener class="myListener"
             file="PATH/TO/YOUR/CODE">
     <arguments>
       <string>build/log</string>
     </arguments>
   </listener>
 </listeners>
Test Listeners               (cont.)



      Implementation example
class ListenerLog implements PHPUnit_Framework_TestListener
{
  public function __construct($path)
  {
    $this->path = $path;
  }

    public function startTestSuite(PHPUnit_Framework_TestSuite $suite)
    {
      $this->log("Test suite '%s' precesed.n", $test->getName());
    }

}
Specialities
Special tests

 Testing exceptions
     @expectedException

 /**
  * @expectedException InvalidArgumentException
  */
 public function testInvalidArgumentException() {

      $obj = new myClass();
      $obj->run('invalidArgument');

 }
Special tests         (cont.)



 Testing exceptions
   setExpectedException( 'Exception' )
     for internal use only!!
     don't use it directly any more.
Special tests              (cont.)



    Testing exceptions
      try/catch
      Does not work when using --strict switch

public function testInvalidArgumentException() {

      $obj = new myClass();
      try{
          $obj->run( 'invalidArgument' );
          $this->fail('Expected exception not thrown.');
      } catch ( InvalidArgumentException $e ) {
      }
}
Special tests            (cont.)


 public function callbackGetObject($name, $className = '')
 {
     retrun strtolower($name) == 'Jakob';
 }

 […]

 $application = $this->getMock('FluentDOM');
 $application
     ->expects($this->any())
     ->method('getObject')
     ->will(
         $this->returnCallback(
             array($this, 'callbackGetObject')
         )
     );
 […]
Special tests             (cont.)



[…]

$application = $this->getMock('FluentDOM');
$application
    ->expects($this->any())
    ->method('getObject')
    ->will(
        $this->onConsecutiveCalls(
            array($this, 'callbackGetObject',
            $this->returnValue(true),
            $this->returnValue(false),
            $this->equalTo($expected)
        )
    );

[…]
Special tests              (cont.)


    implicit integration tests

public function testGet() {

      $mock = $this->getMock(
          'myAbstraction'
      );

      $mock
          ->expected( $this->once() )
          ->method( 'method' )
          ->will( $this->returnValue( 'return' );
}
Questions
@lapistano

lapistano@php.net
Slides'n contact

 Please comment the talk on joind.in
   http://joind.in/3518
 Slides
   http://slideshare.net/lapistano
 Email:
   lapistano@php.net
PHP5.3 Powerworkshop

               New features of PHP5.3
               Best Pratices using OOP
               PHPUnit
               PHPDocumentor
License

    
        This set of slides and the source code included
        in the download package is licensed under the

Creative Commons Attribution-Noncommercial-Share
            Alike 2.0 Generic License


         http://creativecommons.org/licenses/by-nc-sa/2.0/deed.en

More Related Content

PDF
international PHP2011_Bastian Feder_jQuery's Secrets
PDF
jQuery secrets
PDF
Advanced php testing in action
KEY
Php 101: PDO
PDF
PHP Data Objects
PDF
Design Patterns avec PHP 5.3, Symfony et Pimple
PDF
Php unit the-mostunknownparts
PPT
Quebec pdo
international PHP2011_Bastian Feder_jQuery's Secrets
jQuery secrets
Advanced php testing in action
Php 101: PDO
PHP Data Objects
Design Patterns avec PHP 5.3, Symfony et Pimple
Php unit the-mostunknownparts
Quebec pdo

What's hot (20)

PDF
The Origin of Lithium
PDF
Lithium: The Framework for People Who Hate Frameworks
PDF
購物車程式架構簡介
PDF
Design Patterns in PHP5
KEY
Symfony2 Building on Alpha / Beta technology
PDF
Database Design Patterns
PDF
The History of PHPersistence
PDF
The Zen of Lithium
PDF
PhpUnit - The most unknown Parts
PDF
Decoupling with Design Patterns and Symfony2 DIC
PDF
Unittests für Dummies
PDF
Php unit the-mostunknownparts
PDF
Design how your objects talk through mocking
PPTX
Crafting beautiful software
PDF
Unit and Functional Testing with Symfony2
PPT
Mocking Dependencies in PHPUnit
PDF
Dependency Injection IPC 201
PDF
Doctrine fixtures
PDF
Silex meets SOAP & REST
PDF
Dependency injection in PHP 5.3/5.4
The Origin of Lithium
Lithium: The Framework for People Who Hate Frameworks
購物車程式架構簡介
Design Patterns in PHP5
Symfony2 Building on Alpha / Beta technology
Database Design Patterns
The History of PHPersistence
The Zen of Lithium
PhpUnit - The most unknown Parts
Decoupling with Design Patterns and Symfony2 DIC
Unittests für Dummies
Php unit the-mostunknownparts
Design how your objects talk through mocking
Crafting beautiful software
Unit and Functional Testing with Symfony2
Mocking Dependencies in PHPUnit
Dependency Injection IPC 201
Doctrine fixtures
Silex meets SOAP & REST
Dependency injection in PHP 5.3/5.4
Ad

Viewers also liked (12)

PDF
webinale2011_Kai Radusch_Landingpage-Optimierung für Adwords-Kampagnen
PDF
international PHP2011_ilia alshanetsky_Hidden Features of PHP
PDF
international PHP2011_Kore Nordmann_Designing multilingual applications
PDF
webinale2011_Dirk Jesse:Responsive Web Design oder "Unwissenheit ist ein Segen"
PDF
international PHP2011_Bastian Hofmann_Mashing up java script
PPTX
PDF
international PHP2011_Jordi Boggiano_PHP Reset
PDF
Landingpage-Designs die wirklich funktionieren
PPSX
Google adwords ppt by sushen jamwal
PPTX
2015 Google Adwords Training
PDF
Was soll eine Internetseite leisten?
PDF
Keine Klicks Verschenken - auf dem Weg zur optimalen Landingpage
webinale2011_Kai Radusch_Landingpage-Optimierung für Adwords-Kampagnen
international PHP2011_ilia alshanetsky_Hidden Features of PHP
international PHP2011_Kore Nordmann_Designing multilingual applications
webinale2011_Dirk Jesse:Responsive Web Design oder "Unwissenheit ist ein Segen"
international PHP2011_Bastian Hofmann_Mashing up java script
international PHP2011_Jordi Boggiano_PHP Reset
Landingpage-Designs die wirklich funktionieren
Google adwords ppt by sushen jamwal
2015 Google Adwords Training
Was soll eine Internetseite leisten?
Keine Klicks Verschenken - auf dem Weg zur optimalen Landingpage
Ad

Similar to international PHP2011_Bastian Feder_The most unknown Parts of PHPUnit (20)

PDF
Fighting Fear-Driven-Development With PHPUnit
PPT
Unit testing
KEY
Php Unit With Zend Framework Zendcon09
KEY
PHPUnit testing to Zend_Test
PDF
PHPunit and you
PDF
Introduction to Unit Testing with PHPUnit
PDF
Test your code like a pro - PHPUnit in practice
PPTX
Test in action week 2
PPT
Unit Testing using PHPUnit
KEY
Developer testing 101: Become a Testing Fanatic
PPTX
Test in action week 4
KEY
Workshop unittesting
PPT
Test Driven Development with PHPUnit
PPTX
Unit Testng with PHP Unit - A Step by Step Training
PPTX
Getting started-php unit
PDF
Leveling Up With Unit Testing - LonghornPHP 2022
ZIP
Test
PDF
The state of PHPUnit
PPTX
PDF
Unit testing with PHPUnit
Fighting Fear-Driven-Development With PHPUnit
Unit testing
Php Unit With Zend Framework Zendcon09
PHPUnit testing to Zend_Test
PHPunit and you
Introduction to Unit Testing with PHPUnit
Test your code like a pro - PHPUnit in practice
Test in action week 2
Unit Testing using PHPUnit
Developer testing 101: Become a Testing Fanatic
Test in action week 4
Workshop unittesting
Test Driven Development with PHPUnit
Unit Testng with PHP Unit - A Step by Step Training
Getting started-php unit
Leveling Up With Unit Testing - LonghornPHP 2022
Test
The state of PHPUnit
Unit testing with PHPUnit

More from smueller_sandsmedia (6)

PDF
webinale 2011_Gabriel Yoran_Der Schlüssel zum erfolg: Besser aussehen, als ma...
PDF
international PHP2011_Henning Wolf_ Mit Retrospektivenzu erfolgreichen Projekten
PDF
international PHP2011_Kore Nordmann_Tobias Schlitt_Modular Application Archit...
PDF
webinale2011_Chris Mills_Brave new world of HTML5Html5
PDF
international PHP2011_J.Hartmann_DevOps für PHP
PDF
webinale2011_Daniel Höpfner_Förderprogramme für dummies
webinale 2011_Gabriel Yoran_Der Schlüssel zum erfolg: Besser aussehen, als ma...
international PHP2011_Henning Wolf_ Mit Retrospektivenzu erfolgreichen Projekten
international PHP2011_Kore Nordmann_Tobias Schlitt_Modular Application Archit...
webinale2011_Chris Mills_Brave new world of HTML5Html5
international PHP2011_J.Hartmann_DevOps für PHP
webinale2011_Daniel Höpfner_Förderprogramme für dummies

Recently uploaded (20)

PDF
Building Integrated photovoltaic BIPV_UPV.pdf
PDF
Mobile App Security Testing_ A Comprehensive Guide.pdf
PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
PPTX
Digital-Transformation-Roadmap-for-Companies.pptx
PDF
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
PPTX
20250228 LYD VKU AI Blended-Learning.pptx
PDF
Electronic commerce courselecture one. Pdf
PPT
“AI and Expert System Decision Support & Business Intelligence Systems”
PDF
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
PDF
Unlocking AI with Model Context Protocol (MCP)
PDF
NewMind AI Monthly Chronicles - July 2025
PDF
Modernizing your data center with Dell and AMD
PPTX
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
PPTX
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
PDF
Empathic Computing: Creating Shared Understanding
PDF
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
PDF
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
PDF
cuic standard and advanced reporting.pdf
PDF
NewMind AI Weekly Chronicles - August'25 Week I
Building Integrated photovoltaic BIPV_UPV.pdf
Mobile App Security Testing_ A Comprehensive Guide.pdf
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
Digital-Transformation-Roadmap-for-Companies.pptx
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
20250228 LYD VKU AI Blended-Learning.pptx
Electronic commerce courselecture one. Pdf
“AI and Expert System Decision Support & Business Intelligence Systems”
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
Unlocking AI with Model Context Protocol (MCP)
NewMind AI Monthly Chronicles - July 2025
Modernizing your data center with Dell and AMD
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
Empathic Computing: Creating Shared Understanding
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
Diabetes mellitus diagnosis method based random forest with bat algorithm
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
cuic standard and advanced reporting.pdf
NewMind AI Weekly Chronicles - August'25 Week I

international PHP2011_Bastian Feder_The most unknown Parts of PHPUnit

  • 1. The most unknown parts of PHPUnit Bastian Feder IPC Spring 2011 Berlinl lapistano@php.net 1st June 2011
  • 2. Me, myself & I JavaScript since 2002 PHP since 2001 Trainer & coach Opensource addict PHP manual translations FluentDOM ...
  • 3. CLI
  • 4. … on the command line -- testdox[-(html|text)] -- filter <pattern> generates a especially styled filters which testsuite to run. test report. $ phpunit --filter Handler --testdox ./ PHPUnit 3.4.15 by Sebastian Bergmann. FluentDOMCore [x] Get handler FluentDOMHandler [x] Insert nodes after [x] Insert nodes before
  • 5. … on the command line (cont.) -- strict marks test without an assertion as incomplete. Use in combination with –verbose to get the name of the test. -- coverage-(html|source|clover) <(dir|file)> generates a report on how many lines of the code has how often been executed. -- group <groupname [, groupname]> runs only the named group(s). -- d key[=value] alter ini-settings (e.g. memory_limit, max_execution_time)
  • 7. Annotations „In software programming, annotations are used mainly for the purpose of expanding code documentation and comments. They are typically ignored when the code is compiled or executed.“ ( Wikipedia: http://en.wikipedia.org/w/index.php?title=Annotation&oldid=385076084 )
  • 8. Annotations (cont.) /** @covers, @group * @covers myClass::run * @group exceptions * @group Trac-123 */ public function testInvalidArgumentException() { $obj = new myClass(); try{ $obj->run( 'invalidArgument' ); $this->fail('Expected exception not thrown.'); } catch ( InvalidArgumentException $e ) { } }
  • 9. Annotations (cont.) Depending on other tests public function testIsApcAvailable() { if ( ! extension_loaded( 'apc' ) ) { $this->markTestSkipped( 'Required APC not available' ); } } /** * @depend testIsApcAvailable */ public function testGetFileFromAPC () { }
  • 11. Assertions „In computer programming, an assertion is a predicate (for example a true–false statement) placed in a program to indicate that the developer thinks that the predicate is always true at that place. [...] It may be used to verify that an assumption made by the programmer during the implementation of the program remains valid when the program is executed.. [...]“ (Wikipedia, http://en.wikipedia.org/w/index.php?title=Assertion_(computing)&oldid=382473744)
  • 12. Assertions (cont.) assertContains(), assertContainsOnly() Cameleon within the asserts, handles Strings ( like strpos() ) Arrays ( like in_array() ) $this->assertContains('bar', 'foobar'); // ✓ $this->assertContainsOnly('string', array('1', '2', 3)); // ✗
  • 13. Assertions (cont.) assertXMLFileEqualsXMLFile() assertXMLStringEqualsXMLFile() assertXMLStringEqualsXMLString() $this->assertXMLFileEqualsXMLFile( '/path/to/Expected.xml', '/path/to/Fixture.xml' );
  • 14. Assertions (cont.) $ phpunit XmlFileEqualsXmlFileTest.php PHPUnit 3.4.15 by Sebastian Bergmann. … 1) XmlFileEqualsXmlFileTest::testFailure Failed asserting that two strings are equal. --- Expected +++ Actual @@ -1,4 +1,4 @@ <?xml version="1.0"?> <foo> - <bar/> + <baz/> </foo> /dev/tests/XmlFileEqualsXmlFileTest.php:7
  • 15. Assertions (cont.) assertAttribute*() Asserts the content of a class attribute regardless its visibility […] private $collection = array( 1, 2, '3' ); private $name = 'Jakob'; […] $this->assertAttributeContainsOnly( 'integer', 'collection', new myClass ); $this->assertAttributeContains( 'ko', 'name', new myClass );
  • 16. Assertions (cont.) assertType() // TYPE_OBJECT $this->assertType( 'FluentDOM', new FluentDOM ); $this->assertInstanceOf( 'FluentDOM', new FluentDOM ); // TYPE_STRING $this->assertInternalType( 'string', '4221' ); // TYPE_INTEGER $this->assertInternalType( 'integer', 4221 ); // TYPE_RESSOURCE $this->assertInternalType( 'resource', fopen('/file.txt', 'r' );
  • 17. Assertions (cont.) assertSelectRegExp() $xml = ' <items version="1.0"> <persons> <person class="firstname">Thomas</person> <person class="firstname">Jakob</person> <person class="firstname">Bastian</person> </persons> </items> '; $this->assertSelectRegExp( 'person[class*="name"]','(Jakob|Bastian)', 2, $xml);
  • 18. Assertions (cont.) assertThat() Evaluates constraints to build complex assertions. $this->assertThat( $expected, $ths->logicalAnd( $this->isInstanceOf('tire'), $this->logicalNot( $this->identicalTo($myFrontTire) ) ) );
  • 20. Test Listeners Get called on several states of the test runner startTest endTest addIncompleteTest …
  • 21. Test Listeners (cont.) Configuration Add to your phpunit.xml <listeners> <listener class="myListener" file="PATH/TO/YOUR/CODE"> <arguments> <string>build/log</string> </arguments> </listener> </listeners>
  • 22. Test Listeners (cont.) Implementation example class ListenerLog implements PHPUnit_Framework_TestListener { public function __construct($path) { $this->path = $path; } public function startTestSuite(PHPUnit_Framework_TestSuite $suite) { $this->log("Test suite '%s' precesed.n", $test->getName()); } }
  • 24. Special tests Testing exceptions @expectedException /** * @expectedException InvalidArgumentException */ public function testInvalidArgumentException() { $obj = new myClass(); $obj->run('invalidArgument'); }
  • 25. Special tests (cont.) Testing exceptions setExpectedException( 'Exception' ) for internal use only!! don't use it directly any more.
  • 26. Special tests (cont.) Testing exceptions try/catch Does not work when using --strict switch public function testInvalidArgumentException() { $obj = new myClass(); try{ $obj->run( 'invalidArgument' ); $this->fail('Expected exception not thrown.'); } catch ( InvalidArgumentException $e ) { } }
  • 27. Special tests (cont.) public function callbackGetObject($name, $className = '') { retrun strtolower($name) == 'Jakob'; } […] $application = $this->getMock('FluentDOM'); $application ->expects($this->any()) ->method('getObject') ->will( $this->returnCallback( array($this, 'callbackGetObject') ) ); […]
  • 28. Special tests (cont.) […] $application = $this->getMock('FluentDOM'); $application ->expects($this->any()) ->method('getObject') ->will( $this->onConsecutiveCalls( array($this, 'callbackGetObject', $this->returnValue(true), $this->returnValue(false), $this->equalTo($expected) ) ); […]
  • 29. Special tests (cont.) implicit integration tests public function testGet() { $mock = $this->getMock( 'myAbstraction' ); $mock ->expected( $this->once() ) ->method( 'method' ) ->will( $this->returnValue( 'return' ); }
  • 31. Slides'n contact Please comment the talk on joind.in http://joind.in/3518 Slides http://slideshare.net/lapistano Email: lapistano@php.net
  • 32. PHP5.3 Powerworkshop New features of PHP5.3 Best Pratices using OOP PHPUnit PHPDocumentor
  • 33. License  This set of slides and the source code included in the download package is licensed under the Creative Commons Attribution-Noncommercial-Share Alike 2.0 Generic License http://creativecommons.org/licenses/by-nc-sa/2.0/deed.en