SlideShare a Scribd company logo
1 of 33
Download to read offline
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

What's hot

Design Patterns in PHP5
Design Patterns in PHP5 Design Patterns in PHP5
Design Patterns in PHP5
Wildan Maulana
 
Unit and Functional Testing with Symfony2
Unit and Functional Testing with Symfony2Unit and Functional Testing with Symfony2
Unit and Functional Testing with Symfony2
Fabien Potencier
 
Dependency Injection IPC 201
Dependency Injection IPC 201Dependency Injection IPC 201
Dependency Injection IPC 201
Fabien Potencier
 
Doctrine fixtures
Doctrine fixturesDoctrine fixtures
Doctrine fixtures
Bill Chang
 
Dependency injection in PHP 5.3/5.4
Dependency injection in PHP 5.3/5.4Dependency injection in PHP 5.3/5.4
Dependency injection in PHP 5.3/5.4
Fabien Potencier
 

What's hot (20)

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

Viewers also liked

webinale2011_Kai Radusch_Landingpage-Optimierung für Adwords-Kampagnen
webinale2011_Kai Radusch_Landingpage-Optimierung für Adwords-Kampagnenwebinale2011_Kai Radusch_Landingpage-Optimierung für Adwords-Kampagnen
webinale2011_Kai Radusch_Landingpage-Optimierung für Adwords-Kampagnen
smueller_sandsmedia
 
international PHP2011_ilia alshanetsky_Hidden Features of PHP
international PHP2011_ilia alshanetsky_Hidden Features of PHPinternational PHP2011_ilia alshanetsky_Hidden Features of PHP
international PHP2011_ilia alshanetsky_Hidden Features of PHP
smueller_sandsmedia
 
international PHP2011_Kore Nordmann_Designing multilingual applications
international PHP2011_Kore Nordmann_Designing multilingual applications international PHP2011_Kore Nordmann_Designing multilingual applications
international PHP2011_Kore Nordmann_Designing multilingual applications
smueller_sandsmedia
 
webinale2011_Dirk Jesse:Responsive Web Design oder "Unwissenheit ist ein Segen"
webinale2011_Dirk Jesse:Responsive Web Design oder "Unwissenheit ist ein Segen"webinale2011_Dirk Jesse:Responsive Web Design oder "Unwissenheit ist ein Segen"
webinale2011_Dirk Jesse:Responsive Web Design oder "Unwissenheit ist ein Segen"
smueller_sandsmedia
 
international PHP2011_Bastian Hofmann_Mashing up java script
international PHP2011_Bastian Hofmann_Mashing up java scriptinternational PHP2011_Bastian Hofmann_Mashing up java script
international PHP2011_Bastian Hofmann_Mashing up java script
smueller_sandsmedia
 
international PHP2011_Jordi Boggiano_PHP Reset
international PHP2011_Jordi Boggiano_PHP Resetinternational PHP2011_Jordi Boggiano_PHP Reset
international PHP2011_Jordi Boggiano_PHP Reset
smueller_sandsmedia
 

Viewers also liked (12)

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

Similar to international PHP2011_Bastian Feder_The most unknown Parts of PHPUnit

Unit Testing using PHPUnit
Unit Testing using  PHPUnitUnit Testing using  PHPUnit
Unit Testing using PHPUnit
varuntaliyan
 
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
Enterprise PHP Center
 
vfsStream - effective filesystem mocking
vfsStream - effective filesystem mocking vfsStream - effective filesystem mocking
vfsStream - effective filesystem mocking
Sebastian Marek
 
Test in action week 2
Test in action   week 2Test in action   week 2
Test in action week 2
Yi-Huan Chan
 
Mocking Dependencies in PHPUnit
Mocking Dependencies in PHPUnitMocking Dependencies in PHPUnit
Mocking Dependencies in PHPUnit
mfrost503
 

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

Unit testing zend framework apps
Unit testing zend framework appsUnit testing zend framework apps
Unit testing zend framework apps
 
Unit Testing using PHPUnit
Unit Testing using  PHPUnitUnit Testing using  PHPUnit
Unit Testing using PHPUnit
 
PHPunit and you
PHPunit and youPHPunit and you
PHPunit and you
 
Unit testing with zend framework tek11
Unit testing with zend framework tek11Unit testing with zend framework tek11
Unit testing with zend framework tek11
 
Unit testing with zend framework PHPBenelux
Unit testing with zend framework PHPBeneluxUnit testing with zend framework PHPBenelux
Unit testing with zend framework PHPBenelux
 
Symfony2, creare bundle e valore per il cliente
Symfony2, creare bundle e valore per il clienteSymfony2, creare bundle e valore per il cliente
Symfony2, creare bundle e valore per il cliente
 
Test driven development_for_php
Test driven development_for_phpTest driven development_for_php
Test driven development_for_php
 
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
 
vfsStream - effective filesystem mocking
vfsStream - effective filesystem mocking vfsStream - effective filesystem mocking
vfsStream - effective filesystem mocking
 
Test in action week 2
Test in action   week 2Test in action   week 2
Test in action week 2
 
Mocking Dependencies in PHPUnit
Mocking Dependencies in PHPUnitMocking Dependencies in PHPUnit
Mocking Dependencies in PHPUnit
 
PHP Traits
PHP TraitsPHP Traits
PHP Traits
 
PHPUnit best practices presentation
PHPUnit best practices presentationPHPUnit best practices presentation
PHPUnit best practices presentation
 
Unit testing after Zend Framework 1.8
Unit testing after Zend Framework 1.8Unit testing after Zend Framework 1.8
Unit testing after Zend Framework 1.8
 
Refactoring using Codeception
Refactoring using CodeceptionRefactoring using Codeception
Refactoring using Codeception
 
PHPUnit testing to Zend_Test
PHPUnit testing to Zend_TestPHPUnit testing to Zend_Test
PHPUnit testing to Zend_Test
 
Advanced symfony Techniques
Advanced symfony TechniquesAdvanced symfony Techniques
Advanced symfony Techniques
 
Perforce Object and Record Model
Perforce Object and Record Model  Perforce Object and Record Model
Perforce Object and Record Model
 
Php Unit With Zend Framework Zendcon09
Php Unit With Zend Framework   Zendcon09Php Unit With Zend Framework   Zendcon09
Php Unit With Zend Framework Zendcon09
 
Can't Miss Features of PHP 5.3 and 5.4
Can't Miss Features of PHP 5.3 and 5.4Can't Miss Features of PHP 5.3 and 5.4
Can't Miss Features of PHP 5.3 and 5.4
 

More from smueller_sandsmedia

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

More from smueller_sandsmedia (6)

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

Recently uploaded

EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
Earley Information Science
 
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
giselly40
 

Recently uploaded (20)

EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
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
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
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
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
[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
 
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
 
Evaluating the top large language models.pdf
Evaluating the top large language models.pdfEvaluating the top large language models.pdf
Evaluating the top large language models.pdf
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdf
 
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
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 

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