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
PhpUnit - The most unknown Parts
KEY
Workshop unittesting
PDF
Advanced php testing in action
PDF
international PHP2011_Bastian Feder_jQuery's Secrets
PPTX
PHP Traits
PDF
Testing Code and Assuring Quality
PDF
Php unit the-mostunknownparts
PDF
購物車程式架構簡介
PhpUnit - The most unknown Parts
Workshop unittesting
Advanced php testing in action
international PHP2011_Bastian Feder_jQuery's Secrets
PHP Traits
Testing Code and Assuring Quality
Php unit the-mostunknownparts
購物車程式架構簡介

What's hot (18)

PPTX
Adding Dependency Injection to Legacy Applications
KEY
Can't Miss Features of PHP 5.3 and 5.4
PDF
jQuery secrets
PDF
PHPCon 2016: PHP7 by Witek Adamus / XSolve
KEY
Good Evils In Perl (Yapc Asia)
PPT
Quebec pdo
PPT
Mocking Dependencies in PHPUnit
PPT
Corephpcomponentpresentation 1211425966721657-8
PDF
Functional Structures in PHP
PDF
PHP Data Objects
PDF
Unittests für Dummies
KEY
Php 101: PDO
PDF
Php tips-and-tricks4128
PDF
08 Advanced PHP #burningkeyboards
PDF
Melhorando sua API com DSLs
PPT
Bioinformatica 10-11-2011-p6-bioperl
ODP
vfsStream - effective filesystem mocking
PDF
Smelling your code
Adding Dependency Injection to Legacy Applications
Can't Miss Features of PHP 5.3 and 5.4
jQuery secrets
PHPCon 2016: PHP7 by Witek Adamus / XSolve
Good Evils In Perl (Yapc Asia)
Quebec pdo
Mocking Dependencies in PHPUnit
Corephpcomponentpresentation 1211425966721657-8
Functional Structures in PHP
PHP Data Objects
Unittests für Dummies
Php 101: PDO
Php tips-and-tricks4128
08 Advanced PHP #burningkeyboards
Melhorando sua API com DSLs
Bioinformatica 10-11-2011-p6-bioperl
vfsStream - effective filesystem mocking
Smelling your code
Ad

Viewers also liked (15)

PPTX
Company Profile of zhongshan xinxin display products.,ltd
PPTX
Web Site and Rich Internet Applications
PDF
Chang7
DOC
Taronja7
PDF
Portfolio_Done
DOC
Vermell4
PPTX
webTender 2.0
PPT
Testing multithreaded java applications for synchronization problems
PPTX
Thesis Defense Final
PDF
1 chemistry analytical_methods
PPTX
Light - Reflection and Refraction Class 10 Physics Complete
PPTX
Digital transformation - it’s really all about the business stupid!
PDF
Diving into HHVM Extensions (php[tek] 2016)
PDF
Dip Your Toes in the Sea of Security (phpDay 2016)
PDF
Climbing the Abstract Syntax Tree (Bulgaria PHP 2016)
Company Profile of zhongshan xinxin display products.,ltd
Web Site and Rich Internet Applications
Chang7
Taronja7
Portfolio_Done
Vermell4
webTender 2.0
Testing multithreaded java applications for synchronization problems
Thesis Defense Final
1 chemistry analytical_methods
Light - Reflection and Refraction Class 10 Physics Complete
Digital transformation - it’s really all about the business stupid!
Diving into HHVM Extensions (php[tek] 2016)
Dip Your Toes in the Sea of Security (phpDay 2016)
Climbing the Abstract Syntax Tree (Bulgaria PHP 2016)
Ad

Similar to Php unit the-mostunknownparts (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
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
PPTX
PHPUnit: from zero to hero
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
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
PHPUnit: from zero to hero

More from Bastian Feder (17)

PDF
JQuery plugin development fundamentals
PDF
Why documentation osidays
PDF
Solid principles
PDF
jQuery secrets
PDF
Introducing TDD to your project
PDF
jQuery's Secrets
PDF
The Beauty and the Beast
PDF
Advanced Eclipse Workshop (held at IPC2010 -spring edition-)
PDF
The beautyandthebeast phpbat2010
PDF
Debugging PHP with xDebug inside of Eclipse PDT 2.1
PDF
Eclipse HandsOn Workshop
PDF
The Beauty And The Beast Php N W09
PDF
Eclipse Pdt2.0 26.05.2009
PDF
Php Development With Eclipde PDT
PDF
Php Documentor The Beauty And The Beast
PDF
Bubbles & Trees with jQuery
ODP
Ajax hands on - Refactoring Google Suggest
JQuery plugin development fundamentals
Why documentation osidays
Solid principles
jQuery secrets
Introducing TDD to your project
jQuery's Secrets
The Beauty and the Beast
Advanced Eclipse Workshop (held at IPC2010 -spring edition-)
The beautyandthebeast phpbat2010
Debugging PHP with xDebug inside of Eclipse PDT 2.1
Eclipse HandsOn Workshop
The Beauty And The Beast Php N W09
Eclipse Pdt2.0 26.05.2009
Php Development With Eclipde PDT
Php Documentor The Beauty And The Beast
Bubbles & Trees with jQuery
Ajax hands on - Refactoring Google Suggest

Recently uploaded (20)

PPTX
Renaissance Architecture: A Journey from Faith to Humanism
PPTX
Introduction to Child Health Nursing – Unit I | Child Health Nursing I | B.Sc...
PDF
Origin of periodic table-Mendeleev’s Periodic-Modern Periodic table
PDF
Pre independence Education in Inndia.pdf
PPTX
human mycosis Human fungal infections are called human mycosis..pptx
PPTX
PPH.pptx obstetrics and gynecology in nursing
PPTX
Cell Structure & Organelles in detailed.
PDF
O7-L3 Supply Chain Operations - ICLT Program
PPTX
Introduction_to_Human_Anatomy_and_Physiology_for_B.Pharm.pptx
PDF
Basic Mud Logging Guide for educational purpose
PDF
STATICS OF THE RIGID BODIES Hibbelers.pdf
PDF
Business Ethics Teaching Materials for college
PPTX
Institutional Correction lecture only . . .
PDF
TR - Agricultural Crops Production NC III.pdf
PPTX
Week 4 Term 3 Study Techniques revisited.pptx
PDF
FourierSeries-QuestionsWithAnswers(Part-A).pdf
PDF
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
PDF
102 student loan defaulters named and shamed – Is someone you know on the list?
PDF
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
PPTX
BOWEL ELIMINATION FACTORS AFFECTING AND TYPES
Renaissance Architecture: A Journey from Faith to Humanism
Introduction to Child Health Nursing – Unit I | Child Health Nursing I | B.Sc...
Origin of periodic table-Mendeleev’s Periodic-Modern Periodic table
Pre independence Education in Inndia.pdf
human mycosis Human fungal infections are called human mycosis..pptx
PPH.pptx obstetrics and gynecology in nursing
Cell Structure & Organelles in detailed.
O7-L3 Supply Chain Operations - ICLT Program
Introduction_to_Human_Anatomy_and_Physiology_for_B.Pharm.pptx
Basic Mud Logging Guide for educational purpose
STATICS OF THE RIGID BODIES Hibbelers.pdf
Business Ethics Teaching Materials for college
Institutional Correction lecture only . . .
TR - Agricultural Crops Production NC III.pdf
Week 4 Term 3 Study Techniques revisited.pptx
FourierSeries-QuestionsWithAnswers(Part-A).pdf
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
102 student loan defaulters named and shamed – Is someone you know on the list?
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
BOWEL ELIMINATION FACTORS AFFECTING AND TYPES

Php unit the-mostunknownparts

  • 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