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

The Origin of Lithium
The Origin of LithiumThe Origin of Lithium
The Origin of LithiumNate Abele
 
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 FrameworksNate Abele
 
購物車程式架構簡介
購物車程式架構簡介購物車程式架構簡介
購物車程式架構簡介Jace Ju
 
Design Patterns in PHP5
Design Patterns in PHP5 Design Patterns in PHP5
Design Patterns in PHP5 Wildan Maulana
 
Symfony2 Building on Alpha / Beta technology
Symfony2 Building on Alpha / Beta technologySymfony2 Building on Alpha / Beta technology
Symfony2 Building on Alpha / Beta technologyDaniel Knell
 
Database Design Patterns
Database Design PatternsDatabase Design Patterns
Database Design PatternsHugo Hamon
 
The History of PHPersistence
The History of PHPersistenceThe History of PHPersistence
The History of PHPersistenceHugo Hamon
 
The Zen of Lithium
The Zen of LithiumThe Zen of Lithium
The Zen of LithiumNate Abele
 
PhpUnit - The most unknown Parts
PhpUnit - The most unknown PartsPhpUnit - The most unknown Parts
PhpUnit - The most unknown PartsBastian Feder
 
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 DICKonstantin Kudryashov
 
Php unit the-mostunknownparts
Php unit the-mostunknownpartsPhp unit the-mostunknownparts
Php unit the-mostunknownpartsBastian Feder
 
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 mockingKonstantin Kudryashov
 
Crafting beautiful software
Crafting beautiful softwareCrafting beautiful software
Crafting beautiful softwareJorn Oomen
 
Unit and Functional Testing with Symfony2
Unit and Functional Testing with Symfony2Unit and Functional Testing with Symfony2
Unit and Functional Testing with Symfony2Fabien Potencier
 
Mocking Dependencies in PHPUnit
Mocking Dependencies in PHPUnitMocking Dependencies in PHPUnit
Mocking Dependencies in PHPUnitmfrost503
 
Dependency Injection IPC 201
Dependency Injection IPC 201Dependency Injection IPC 201
Dependency Injection IPC 201Fabien Potencier
 
Doctrine fixtures
Doctrine fixturesDoctrine fixtures
Doctrine fixturesBill Chang
 
Silex meets SOAP & REST
Silex meets SOAP & RESTSilex meets SOAP & REST
Silex meets SOAP & RESTHugo Hamon
 
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.4Fabien 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-Kampagnensmueller_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 PHPsmueller_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 scriptsmueller_sandsmedia
 
international PHP2011_Jordi Boggiano_PHP Reset
international PHP2011_Jordi Boggiano_PHP Resetinternational PHP2011_Jordi Boggiano_PHP Reset
international PHP2011_Jordi Boggiano_PHP Resetsmueller_sandsmedia
 
Landingpage-Designs die wirklich funktionieren
Landingpage-Designs die wirklich funktionierenLandingpage-Designs die wirklich funktionieren
Landingpage-Designs die wirklich funktionierenConversionBoosting
 
Google adwords ppt by sushen jamwal
Google adwords ppt by sushen jamwalGoogle adwords ppt by sushen jamwal
Google adwords ppt by sushen jamwalSushen Jamwal
 
Was soll eine Internetseite leisten?
Was soll eine Internetseite leisten?Was soll eine Internetseite leisten?
Was soll eine Internetseite leisten?Christof Ortmann
 
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 LandingpageDaniel Reckling
 

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 PHPUnitvaruntaliyan
 
PHPunit and you
PHPunit and youPHPunit and you
PHPunit and youmarkstory
 
Unit testing with zend framework tek11
Unit testing with zend framework tek11Unit testing with zend framework tek11
Unit testing with zend framework tek11Michelangelo van Dam
 
Unit testing with zend framework PHPBenelux
Unit testing with zend framework PHPBeneluxUnit testing with zend framework PHPBenelux
Unit testing with zend framework PHPBeneluxMichelangelo van Dam
 
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 clienteLeonardo Proietti
 
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
 
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 2Yi-Huan Chan
 
Mocking Dependencies in PHPUnit
Mocking Dependencies in PHPUnitMocking Dependencies in PHPUnit
Mocking Dependencies in PHPUnitmfrost503
 
PHP Traits
PHP TraitsPHP Traits
PHP Traitsmattbuzz
 
PHPUnit best practices presentation
PHPUnit best practices presentationPHPUnit best practices presentation
PHPUnit best practices presentationThanh Robi
 
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.8Michelangelo van Dam
 
Refactoring using Codeception
Refactoring using CodeceptionRefactoring using Codeception
Refactoring using CodeceptionJeroen van Dijk
 
Advanced symfony Techniques
Advanced symfony TechniquesAdvanced symfony Techniques
Advanced symfony TechniquesKris Wallsmith
 
Perforce Object and Record Model
Perforce Object and Record Model  Perforce Object and Record Model
Perforce Object and Record Model Perforce
 
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
 
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.4Jeff Carouth
 

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 Projektensmueller_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 HTML5Html5smueller_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 PHPsmueller_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 dummiessmueller_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

Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 3652toLead Limited
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
costume and set research powerpoint presentation
costume and set research powerpoint presentationcostume and set research powerpoint presentation
costume and set research powerpoint presentationphoebematthew05
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsMiki Katsuragi
 
APIForce Zurich 5 April Automation LPDG
APIForce Zurich 5 April  Automation LPDGAPIForce Zurich 5 April  Automation LPDG
APIForce Zurich 5 April Automation LPDGMarianaLemus7
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 

Recently uploaded (20)

Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
costume and set research powerpoint presentation
costume and set research powerpoint presentationcostume and set research powerpoint presentation
costume and set research powerpoint presentation
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering Tips
 
APIForce Zurich 5 April Automation LPDG
APIForce Zurich 5 April  Automation LPDGAPIForce Zurich 5 April  Automation LPDG
APIForce Zurich 5 April Automation LPDG
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 

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