SlideShare une entreprise Scribd logo
1  sur  27
The most unknown parts of
PHPUnit




Bastian Feder           Confoo 2011 Montreal
bastian.feder@liip.ch        11th March 2011
… 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.)



 -- stop-on-failure
 stops the testrun on the first recognized failure.
 -- 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)
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('baz', '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.)



 assertObjectHasAttribute(), assertClassHasAttribute()

 Overcomes visibilty by using Reflection-API
 Testifies the existance of a property,
 not its' content
 $this->assertObjectHasAttribute(
     'myPrivateAttribute', new stdClass() );

 $this->assertObjectHasAttribute(
     'myPrivateAttribute', 'stdClass' );
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 FluentDOM );

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



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

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

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

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

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


 assertSelectEquals(), assertSelectCount()

 Assert the presence, absence, or count of elements in a
 document.
 Uses CSS selectors to select DOMNodes
 Handles XML and HTML
 $this->assertSelectEquals(
     '#myElement', 'myContent', 3, $xml );

 $this->assertSelectCount( '#myElement', false, $xml );
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)
         )
     )
 );
Inverted Assertions

 Mostly every assertion has an inverted sibling.
 assertNotContains()
 assertNotThat()
 assertAttributeNotSame()
 …
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.)



    @depends
public function testIsApcAvailable() {

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

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

}
Special tests

 Testing exceptions
     @expectedException

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

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

 }
Special tests              (cont.)



    Testing exceptions
      setExpectedException( 'Exception' )


public function testInvalidArgumentException() {

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

}
Special tests              (cont.)



    Testing exceptions
      try/catch

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')?: false;
 }

 […]

 $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',
          array( 'method' )
      );

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

lapistano@php.net
Slides'n contact

 Please comment the talk on joind.in
   http://joind.in/2879
   http://joind.in/2848
 Slides
   http://slideshare.net/lapistano
 Email:
   bastian.feder@liip.ch
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

Contenu connexe

Tendances

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
 
Corephpcomponentpresentation 1211425966721657-8
Corephpcomponentpresentation 1211425966721657-8Corephpcomponentpresentation 1211425966721657-8
Corephpcomponentpresentation 1211425966721657-8PrinceGuru MS
 
Adding Dependency Injection to Legacy Applications
Adding Dependency Injection to Legacy ApplicationsAdding Dependency Injection to Legacy Applications
Adding Dependency Injection to Legacy ApplicationsSam Hennessy
 
The Zen of Lithium
The Zen of LithiumThe Zen of Lithium
The Zen of LithiumNate Abele
 
Dependency injection - phpday 2010
Dependency injection - phpday 2010Dependency injection - phpday 2010
Dependency injection - phpday 2010Fabien Potencier
 
Command Bus To Awesome Town
Command Bus To Awesome TownCommand Bus To Awesome Town
Command Bus To Awesome TownRoss Tuck
 
The State of Lithium
The State of LithiumThe State of Lithium
The State of LithiumNate Abele
 
Perforce Object and Record Model
Perforce Object and Record Model  Perforce Object and Record Model
Perforce Object and Record Model Perforce
 
Models and Service Layers, Hemoglobin and Hobgoblins
Models and Service Layers, Hemoglobin and HobgoblinsModels and Service Layers, Hemoglobin and Hobgoblins
Models and Service Layers, Hemoglobin and HobgoblinsRoss Tuck
 
R57shell
R57shellR57shell
R57shellady36
 
Lithium: The Framework for People Who Hate Frameworks, Tokyo Edition
Lithium: The Framework for People Who Hate Frameworks, Tokyo EditionLithium: The Framework for People Who Hate Frameworks, Tokyo Edition
Lithium: The Framework for People Who Hate Frameworks, Tokyo EditionNate Abele
 
Php unit the-mostunknownparts
Php unit the-mostunknownpartsPhp unit the-mostunknownparts
Php unit the-mostunknownpartsBastian Feder
 
PHP Data Objects
PHP Data ObjectsPHP Data Objects
PHP Data ObjectsWez Furlong
 
Design Patterns avec PHP 5.3, Symfony et Pimple
Design Patterns avec PHP 5.3, Symfony et PimpleDesign Patterns avec PHP 5.3, Symfony et Pimple
Design Patterns avec PHP 5.3, Symfony et PimpleHugo Hamon
 
Design Patterns in PHP5
Design Patterns in PHP5 Design Patterns in PHP5
Design Patterns in PHP5 Wildan Maulana
 
Dependency Injection with PHP and PHP 5.3
Dependency Injection with PHP and PHP 5.3Dependency Injection with PHP and PHP 5.3
Dependency Injection with PHP and PHP 5.3Fabien Potencier
 

Tendances (20)

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
 
Unittests für Dummies
Unittests für DummiesUnittests für Dummies
Unittests für Dummies
 
Corephpcomponentpresentation 1211425966721657-8
Corephpcomponentpresentation 1211425966721657-8Corephpcomponentpresentation 1211425966721657-8
Corephpcomponentpresentation 1211425966721657-8
 
Oops in php
Oops in phpOops in php
Oops in php
 
Adding Dependency Injection to Legacy Applications
Adding Dependency Injection to Legacy ApplicationsAdding Dependency Injection to Legacy Applications
Adding Dependency Injection to Legacy Applications
 
The Zen of Lithium
The Zen of LithiumThe Zen of Lithium
The Zen of Lithium
 
Dependency injection - phpday 2010
Dependency injection - phpday 2010Dependency injection - phpday 2010
Dependency injection - phpday 2010
 
Command Bus To Awesome Town
Command Bus To Awesome TownCommand Bus To Awesome Town
Command Bus To Awesome Town
 
The State of Lithium
The State of LithiumThe State of Lithium
The State of Lithium
 
Perforce Object and Record Model
Perforce Object and Record Model  Perforce Object and Record Model
Perforce Object and Record Model
 
Models and Service Layers, Hemoglobin and Hobgoblins
Models and Service Layers, Hemoglobin and HobgoblinsModels and Service Layers, Hemoglobin and Hobgoblins
Models and Service Layers, Hemoglobin and Hobgoblins
 
R57shell
R57shellR57shell
R57shell
 
jQuery secrets
jQuery secretsjQuery secrets
jQuery secrets
 
Smelling your code
Smelling your codeSmelling your code
Smelling your code
 
Lithium: The Framework for People Who Hate Frameworks, Tokyo Edition
Lithium: The Framework for People Who Hate Frameworks, Tokyo EditionLithium: The Framework for People Who Hate Frameworks, Tokyo Edition
Lithium: The Framework for People Who Hate Frameworks, Tokyo Edition
 
Php unit the-mostunknownparts
Php unit the-mostunknownpartsPhp unit the-mostunknownparts
Php unit the-mostunknownparts
 
PHP Data Objects
PHP Data ObjectsPHP Data Objects
PHP Data Objects
 
Design Patterns avec PHP 5.3, Symfony et Pimple
Design Patterns avec PHP 5.3, Symfony et PimpleDesign Patterns avec PHP 5.3, Symfony et Pimple
Design Patterns avec PHP 5.3, Symfony et Pimple
 
Design Patterns in PHP5
Design Patterns in PHP5 Design Patterns in PHP5
Design Patterns in PHP5
 
Dependency Injection with PHP and PHP 5.3
Dependency Injection with PHP and PHP 5.3Dependency Injection with PHP and PHP 5.3
Dependency Injection with PHP and PHP 5.3
 

En vedette

IPC 2013 - High Performance PHP with HipHop
IPC 2013 - High Performance PHP with HipHopIPC 2013 - High Performance PHP with HipHop
IPC 2013 - High Performance PHP with HipHopSteve Kamerman
 
PHP Unit y TDD
PHP Unit y TDDPHP Unit y TDD
PHP Unit y TDDEmergya
 
Automated php unit testing in drupal 8
Automated php unit testing in drupal 8Automated php unit testing in drupal 8
Automated php unit testing in drupal 8Jay Friendly
 
PHPUnit with CakePHP and Yii
PHPUnit with CakePHP and YiiPHPUnit with CakePHP and Yii
PHPUnit with CakePHP and Yiimadhavi Ghadge
 
PHPUnit: from zero to hero
PHPUnit: from zero to heroPHPUnit: from zero to hero
PHPUnit: from zero to heroJeremy Cook
 
Automated Testing in WordPress, Really?!
Automated Testing in WordPress, Really?!Automated Testing in WordPress, Really?!
Automated Testing in WordPress, Really?!Ptah Dunbar
 
3 questions you need to ask about your brand
3 questions you need to ask about your brand3 questions you need to ask about your brand
3 questions you need to ask about your brand114iiminternship
 
Curso de Posicionamiento y Marketing de buscadores: SEO, SEM y Analítica
Curso de Posicionamiento y Marketing de buscadores: SEO, SEM y AnalíticaCurso de Posicionamiento y Marketing de buscadores: SEO, SEM y Analítica
Curso de Posicionamiento y Marketing de buscadores: SEO, SEM y AnalíticaIEBSchool
 
Ende, michael jim boton y lucas el maquinista204pags.
Ende, michael   jim boton y lucas el maquinista204pags.Ende, michael   jim boton y lucas el maquinista204pags.
Ende, michael jim boton y lucas el maquinista204pags.Cuentos Universales
 
Informe público barómetro marca ciudad 2011
Informe público barómetro marca ciudad 2011Informe público barómetro marca ciudad 2011
Informe público barómetro marca ciudad 2011Visión Humana
 

En vedette (20)

chapters
chapterschapters
chapters
 
IPC 2013 - High Performance PHP with HipHop
IPC 2013 - High Performance PHP with HipHopIPC 2013 - High Performance PHP with HipHop
IPC 2013 - High Performance PHP with HipHop
 
PHPUnit
PHPUnitPHPUnit
PHPUnit
 
PHP Unit y TDD
PHP Unit y TDDPHP Unit y TDD
PHP Unit y TDD
 
Automated php unit testing in drupal 8
Automated php unit testing in drupal 8Automated php unit testing in drupal 8
Automated php unit testing in drupal 8
 
PHPUnit with CakePHP and Yii
PHPUnit with CakePHP and YiiPHPUnit with CakePHP and Yii
PHPUnit with CakePHP and Yii
 
PHPUnit: from zero to hero
PHPUnit: from zero to heroPHPUnit: from zero to hero
PHPUnit: from zero to hero
 
Automated Testing in WordPress, Really?!
Automated Testing in WordPress, Really?!Automated Testing in WordPress, Really?!
Automated Testing in WordPress, Really?!
 
CV TEC. ELECT DELMER
CV TEC. ELECT  DELMERCV TEC. ELECT  DELMER
CV TEC. ELECT DELMER
 
3 questions you need to ask about your brand
3 questions you need to ask about your brand3 questions you need to ask about your brand
3 questions you need to ask about your brand
 
Curso de Posicionamiento y Marketing de buscadores: SEO, SEM y Analítica
Curso de Posicionamiento y Marketing de buscadores: SEO, SEM y AnalíticaCurso de Posicionamiento y Marketing de buscadores: SEO, SEM y Analítica
Curso de Posicionamiento y Marketing de buscadores: SEO, SEM y Analítica
 
Moción instituciona lcarril de orozco febrero 2016
Moción instituciona lcarril de orozco febrero 2016Moción instituciona lcarril de orozco febrero 2016
Moción instituciona lcarril de orozco febrero 2016
 
Ende, michael jim boton y lucas el maquinista204pags.
Ende, michael   jim boton y lucas el maquinista204pags.Ende, michael   jim boton y lucas el maquinista204pags.
Ende, michael jim boton y lucas el maquinista204pags.
 
Logo design1
Logo design1Logo design1
Logo design1
 
AJS direct mail piece
AJS direct mail pieceAJS direct mail piece
AJS direct mail piece
 
ORGANOS DE LOS SENTIDOS
ORGANOS DE LOS SENTIDOSORGANOS DE LOS SENTIDOS
ORGANOS DE LOS SENTIDOS
 
IPL Brochure
IPL BrochureIPL Brochure
IPL Brochure
 
Informe público barómetro marca ciudad 2011
Informe público barómetro marca ciudad 2011Informe público barómetro marca ciudad 2011
Informe público barómetro marca ciudad 2011
 
Ramón Cabanillas
Ramón CabanillasRamón Cabanillas
Ramón Cabanillas
 
dgaweb
dgawebdgaweb
dgaweb
 

Similaire à PhpUnit - The most unknown Parts

international PHP2011_Bastian Feder_The most unknown Parts of PHPUnit
international PHP2011_Bastian Feder_The most unknown Parts of PHPUnitinternational PHP2011_Bastian Feder_The most unknown Parts of PHPUnit
international PHP2011_Bastian Feder_The most unknown Parts of PHPUnitsmueller_sandsmedia
 
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
 
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
 
Symfony2 Building on Alpha / Beta technology
Symfony2 Building on Alpha / Beta technologySymfony2 Building on Alpha / Beta technology
Symfony2 Building on Alpha / Beta technologyDaniel Knell
 
Refactoring using Codeception
Refactoring using CodeceptionRefactoring using Codeception
Refactoring using CodeceptionJeroen van Dijk
 
Mocking Dependencies in PHPUnit
Mocking Dependencies in PHPUnitMocking Dependencies in PHPUnit
Mocking Dependencies in PHPUnitmfrost503
 
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
 
PHPunit and you
PHPunit and youPHPunit and you
PHPunit and youmarkstory
 
Why is crud a bad idea - focus on real scenarios
Why is crud a bad idea - focus on real scenariosWhy is crud a bad idea - focus on real scenarios
Why is crud a bad idea - focus on real scenariosDivante
 
vfsStream - effective filesystem mocking
vfsStream - effective filesystem mocking vfsStream - effective filesystem mocking
vfsStream - effective filesystem mocking Sebastian Marek
 
Rich domain model with symfony 2.5 and doctrine 2.5
Rich domain model with symfony 2.5 and doctrine 2.5Rich domain model with symfony 2.5 and doctrine 2.5
Rich domain model with symfony 2.5 and doctrine 2.5Leonardo Proietti
 
Introducing CakeEntity
Introducing CakeEntityIntroducing CakeEntity
Introducing CakeEntityBasuke Suzuki
 
Advanced symfony Techniques
Advanced symfony TechniquesAdvanced symfony Techniques
Advanced symfony TechniquesKris Wallsmith
 
Aura Project for PHP
Aura Project for PHPAura Project for PHP
Aura Project for PHPHari K T
 

Similaire à PhpUnit - The most unknown Parts (20)

international PHP2011_Bastian Feder_The most unknown Parts of PHPUnit
international PHP2011_Bastian Feder_The most unknown Parts of PHPUnitinternational PHP2011_Bastian Feder_The most unknown Parts of PHPUnit
international PHP2011_Bastian Feder_The most unknown Parts of PHPUnit
 
Unit testing with zend framework PHPBenelux
Unit testing with zend framework PHPBeneluxUnit testing with zend framework PHPBenelux
Unit testing with zend framework PHPBenelux
 
Unit testing zend framework apps
Unit testing zend framework appsUnit testing zend framework apps
Unit testing zend framework apps
 
Unit testing with zend framework tek11
Unit testing with zend framework tek11Unit testing with zend framework tek11
Unit testing with zend framework tek11
 
Symfony2 Building on Alpha / Beta technology
Symfony2 Building on Alpha / Beta technologySymfony2 Building on Alpha / Beta technology
Symfony2 Building on Alpha / Beta technology
 
Refactoring using Codeception
Refactoring using CodeceptionRefactoring using Codeception
Refactoring using Codeception
 
Mocking Dependencies in PHPUnit
Mocking Dependencies in PHPUnitMocking Dependencies in PHPUnit
Mocking Dependencies in PHPUnit
 
Separation of concerns - DPC12
Separation of concerns - DPC12Separation of concerns - DPC12
Separation of concerns - DPC12
 
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
 
Intermediate PHP
Intermediate PHPIntermediate PHP
Intermediate PHP
 
PHPSpec BDD for PHP
PHPSpec BDD for PHPPHPSpec BDD for PHP
PHPSpec BDD for PHP
 
PHPunit and you
PHPunit and youPHPunit and you
PHPunit and you
 
Why is crud a bad idea - focus on real scenarios
Why is crud a bad idea - focus on real scenariosWhy is crud a bad idea - focus on real scenarios
Why is crud a bad idea - focus on real scenarios
 
vfsStream - effective filesystem mocking
vfsStream - effective filesystem mocking vfsStream - effective filesystem mocking
vfsStream - effective filesystem mocking
 
Rich domain model with symfony 2.5 and doctrine 2.5
Rich domain model with symfony 2.5 and doctrine 2.5Rich domain model with symfony 2.5 and doctrine 2.5
Rich domain model with symfony 2.5 and doctrine 2.5
 
Introducing CakeEntity
Introducing CakeEntityIntroducing CakeEntity
Introducing CakeEntity
 
Min-Maxing Software Costs
Min-Maxing Software CostsMin-Maxing Software Costs
Min-Maxing Software Costs
 
Advanced symfony Techniques
Advanced symfony TechniquesAdvanced symfony Techniques
Advanced symfony Techniques
 
Aura Project for PHP
Aura Project for PHPAura Project for PHP
Aura Project for PHP
 
Test driven development_for_php
Test driven development_for_phpTest driven development_for_php
Test driven development_for_php
 

Plus de Bastian Feder

JQuery plugin development fundamentals
JQuery plugin development fundamentalsJQuery plugin development fundamentals
JQuery plugin development fundamentalsBastian Feder
 
Why documentation osidays
Why documentation osidaysWhy documentation osidays
Why documentation osidaysBastian Feder
 
Introducing TDD to your project
Introducing TDD to your projectIntroducing TDD to your project
Introducing TDD to your projectBastian Feder
 
The Beauty and the Beast
The Beauty and the BeastThe Beauty and the Beast
The Beauty and the BeastBastian Feder
 
Advanced Eclipse Workshop (held at IPC2010 -spring edition-)
Advanced Eclipse Workshop (held at IPC2010 -spring edition-)Advanced Eclipse Workshop (held at IPC2010 -spring edition-)
Advanced Eclipse Workshop (held at IPC2010 -spring edition-)Bastian Feder
 
The beautyandthebeast phpbat2010
The beautyandthebeast phpbat2010The beautyandthebeast phpbat2010
The beautyandthebeast phpbat2010Bastian Feder
 
Debugging PHP with xDebug inside of Eclipse PDT 2.1
Debugging PHP with xDebug inside of Eclipse PDT 2.1Debugging PHP with xDebug inside of Eclipse PDT 2.1
Debugging PHP with xDebug inside of Eclipse PDT 2.1Bastian Feder
 
Eclipse HandsOn Workshop
Eclipse HandsOn WorkshopEclipse HandsOn Workshop
Eclipse HandsOn WorkshopBastian Feder
 
The Beauty And The Beast Php N W09
The Beauty And The Beast Php N W09The Beauty And The Beast Php N W09
The Beauty And The Beast Php N W09Bastian Feder
 
Eclipse Pdt2.0 26.05.2009
Eclipse Pdt2.0 26.05.2009Eclipse Pdt2.0 26.05.2009
Eclipse Pdt2.0 26.05.2009Bastian Feder
 
Php Development With Eclipde PDT
Php Development With Eclipde PDTPhp Development With Eclipde PDT
Php Development With Eclipde PDTBastian Feder
 
Php Documentor The Beauty And The Beast
Php Documentor The Beauty And The BeastPhp Documentor The Beauty And The Beast
Php Documentor The Beauty And The BeastBastian Feder
 
Bubbles & Trees with jQuery
Bubbles & Trees with jQueryBubbles & Trees with jQuery
Bubbles & Trees with jQueryBastian Feder
 
Ajax hands on - Refactoring Google Suggest
Ajax hands on - Refactoring Google SuggestAjax hands on - Refactoring Google Suggest
Ajax hands on - Refactoring Google SuggestBastian Feder
 

Plus de Bastian Feder (17)

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

Dernier

BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...Sapna Thakur
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAssociation for Project Management
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdfQucHHunhnh
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactPECB
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Krashi Coaching
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfsanyamsingh5019
 
social pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajansocial pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajanpragatimahajan3
 
9548086042 for call girls in Indira Nagar with room service
9548086042  for call girls in Indira Nagar  with room service9548086042  for call girls in Indira Nagar  with room service
9548086042 for call girls in Indira Nagar with room servicediscovermytutordmt
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactdawncurless
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeThiyagu K
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfchloefrazer622
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3JemimahLaneBuaron
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsTechSoup
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...EduSkills OECD
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityGeoBlogs
 
General AI for Medical Educators April 2024
General AI for Medical Educators April 2024General AI for Medical Educators April 2024
General AI for Medical Educators April 2024Janet Corral
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxVishalSingh1417
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhikauryashika82
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationnomboosow
 

Dernier (20)

BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across Sectors
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdf
 
social pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajansocial pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajan
 
9548086042 for call girls in Indira Nagar with room service
9548086042  for call girls in Indira Nagar  with room service9548086042  for call girls in Indira Nagar  with room service
9548086042 for call girls in Indira Nagar with room service
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdf
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
General AI for Medical Educators April 2024
General AI for Medical Educators April 2024General AI for Medical Educators April 2024
General AI for Medical Educators April 2024
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptx
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
 
Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communication
 

PhpUnit - The most unknown Parts

  • 1. The most unknown parts of PHPUnit Bastian Feder Confoo 2011 Montreal bastian.feder@liip.ch 11th March 2011
  • 2. … 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
  • 3. … on the command line (cont.) -- stop-on-failure stops the testrun on the first recognized failure. -- 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)
  • 4. 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)
  • 5. Assertions (cont.) assertContains(), assertContainsOnly() Cameleon within the asserts, handles Strings ( like strpos() ) Arrays ( like in_array() ) $this->assertContains('baz', 'foobar'); $this->assertContainsOnly('string', array('1', '2', 3));
  • 6. Assertions (cont.) assertXMLFileEqualsXMLFile() assertXMLStringEqualsXMLFile() assertXMLStringEqualsXMLString() $this->assertXMLFileEqualsXMLFile( '/path/to/Expected.xml', '/path/to/Fixture.xml' );
  • 7. 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
  • 8. Assertions (cont.) assertObjectHasAttribute(), assertClassHasAttribute() Overcomes visibilty by using Reflection-API Testifies the existance of a property, not its' content $this->assertObjectHasAttribute( 'myPrivateAttribute', new stdClass() ); $this->assertObjectHasAttribute( 'myPrivateAttribute', 'stdClass' );
  • 9. 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 FluentDOM ); $this->assertAttributeContains( 'ko', 'name', new FluentDOM );
  • 10. Assertions (cont.) assertType() // TYPE_OBJECT $this->assertType( 'FluentDOM', new FluentDOM ); $this->assertInstanceOf( 'FluentDOM', new FluentDOM ); // TYPE_STRING $this->assertType( 'string', '4221' ); // TYPE_INTEGER $this->assertType( 'integer', 4221 ); // TYPE_RESSOURCE $this->assertType( 'resource', fopen('/file.txt', 'r' );
  • 11. Assertions (cont.) assertSelectEquals(), assertSelectCount() Assert the presence, absence, or count of elements in a document. Uses CSS selectors to select DOMNodes Handles XML and HTML $this->assertSelectEquals( '#myElement', 'myContent', 3, $xml ); $this->assertSelectCount( '#myElement', false, $xml );
  • 12. 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);
  • 13. Assertions (cont.) assertThat() Evaluates constraints to build complex assertions. $this->assertThat( $expected, $ths->logicalAnd( $this->isInstanceOf('tire'), $this->logicalNot( $this->identicalTo($myFrontTire) ) ) );
  • 14. Inverted Assertions Mostly every assertion has an inverted sibling. assertNotContains() assertNotThat() assertAttributeNotSame() …
  • 15. 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 )
  • 16. 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 ) { } }
  • 17. Annotations (cont.) @depends public function testIsApcAvailable() { if ( ! extension_loaded( 'apc' ) ) { $this->markTestSkipped( 'Required APC not available' ); } } /** * @depend testIsApcAvailable */ public function testGetFileFromAPC () { }
  • 18. Special tests Testing exceptions @expectedException /** * @expectedException InvalidArgumentException */ public function testInvalidArgumentException() { $obj = new myClass(); $obj->run('invalidArgument'); }
  • 19. Special tests (cont.) Testing exceptions setExpectedException( 'Exception' ) public function testInvalidArgumentException() { $this->setExpectedException('InvalidArgumentException ') $obj = new myClass(); $obj->run('invalidArgument'); }
  • 20. Special tests (cont.) Testing exceptions try/catch public function testInvalidArgumentException() { $obj = new myClass(); try{ $obj->run( 'invalidArgument' ); $this->fail('Expected exception not thrown.'); } catch ( InvalidArgumentException $e ) { } }
  • 21. Special tests (cont.) public function callbackGetObject($name, $className = '') { retrun (strtolower($name) == 'Jakob')?: false; } […] $application = $this->getMock('FluentDOM'); $application ->expects($this->any()) ->method('getObject') ->will( $this->returnCallback( array($this, 'callbackGetObject') ) ); […]
  • 22. 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) ) ); […]
  • 23. Special tests (cont.) implicit integration tests public function testGet() { $mock = $this->getMock( 'myAbstraction', array( 'method' ) ); $mock ->expected( $this->once() ) ->method( 'methoSd' ) ->will( $this->returnValue( 'return' ); }
  • 25. Slides'n contact Please comment the talk on joind.in http://joind.in/2879 http://joind.in/2848 Slides http://slideshare.net/lapistano Email: bastian.feder@liip.ch
  • 26. PHP5.3 Powerworkshop New features of PHP5.3 Best Pratices using OOP PHPUnit PHPDocumentor
  • 27. 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