SlideShare ist ein Scribd-Unternehmen logo
1 von 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

Weitere ähnliche Inhalte

Was ist angesagt?

Corephpcomponentpresentation 1211425966721657-8
Corephpcomponentpresentation 1211425966721657-8Corephpcomponentpresentation 1211425966721657-8
Corephpcomponentpresentation 1211425966721657-8
PrinceGuru MS
 
Dependency injection - phpday 2010
Dependency injection - phpday 2010Dependency injection - phpday 2010
Dependency injection - phpday 2010
Fabien Potencier
 
R57shell
R57shellR57shell
R57shell
ady36
 
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.3
Fabien Potencier
 

Was ist angesagt? (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
 

Andere mochten auch

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 2011
Visión Humana
 

Andere mochten auch (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
 

Ähnlich wie 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 PHPUnit
smueller_sandsmedia
 
Mocking Dependencies in PHPUnit
Mocking Dependencies in PHPUnitMocking Dependencies in PHPUnit
Mocking Dependencies in PHPUnit
mfrost503
 
vfsStream - effective filesystem mocking
vfsStream - effective filesystem mocking vfsStream - effective filesystem mocking
vfsStream - effective filesystem mocking
Sebastian Marek
 
Aura Project for PHP
Aura Project for PHPAura Project for PHP
Aura Project for PHP
Hari K T
 

Ähnlich wie 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
 

Mehr von Bastian Feder

Eclipse HandsOn Workshop
Eclipse HandsOn WorkshopEclipse HandsOn Workshop
Eclipse HandsOn Workshop
Bastian Feder
 

Mehr von 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
 

Kürzlich hochgeladen

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
kauryashika82
 
Gardella_PRCampaignConclusion Pitch Letter
Gardella_PRCampaignConclusion Pitch LetterGardella_PRCampaignConclusion Pitch Letter
Gardella_PRCampaignConclusion Pitch Letter
MateoGardella
 
Making and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdfMaking and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdf
Chris Hunter
 
Seal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxSeal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptx
negromaestrong
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
heathfieldcps1
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
QucHHunhnh
 
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
PECB
 

Kürzlich hochgeladen (20)

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
 
Class 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfClass 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdf
 
Gardella_PRCampaignConclusion Pitch Letter
Gardella_PRCampaignConclusion Pitch LetterGardella_PRCampaignConclusion Pitch Letter
Gardella_PRCampaignConclusion Pitch Letter
 
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
 
Making and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdfMaking and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdf
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
fourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writingfourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writing
 
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
 
Seal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxSeal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptx
 
Advance Mobile Application Development class 07
Advance Mobile Application Development class 07Advance Mobile Application Development class 07
Advance Mobile Application Development class 07
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17
 
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . 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
 
Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024
 
SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...
SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...
SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...
 

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