SlideShare a Scribd company logo
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

More Related Content

What's hot (20)

PDF
Lithium: The Framework for People Who Hate Frameworks
Nate Abele
 
PDF
Unittests für Dummies
Lars Jankowfsky
 
PPT
Corephpcomponentpresentation 1211425966721657-8
PrinceGuru MS
 
PPTX
Oops in php
Gourishankar R Pujar
 
PPTX
Adding Dependency Injection to Legacy Applications
Sam Hennessy
 
PDF
The Zen of Lithium
Nate Abele
 
PDF
Dependency injection - phpday 2010
Fabien Potencier
 
PDF
Command Bus To Awesome Town
Ross Tuck
 
PDF
The State of Lithium
Nate Abele
 
PDF
Perforce Object and Record Model
Perforce
 
PDF
Models and Service Layers, Hemoglobin and Hobgoblins
Ross Tuck
 
PDF
R57shell
ady36
 
PDF
jQuery secrets
Bastian Feder
 
PDF
Smelling your code
Raju Mazumder
 
PDF
Lithium: The Framework for People Who Hate Frameworks, Tokyo Edition
Nate Abele
 
PDF
Php unit the-mostunknownparts
Bastian Feder
 
PDF
PHP Data Objects
Wez Furlong
 
PDF
Design Patterns avec PHP 5.3, Symfony et Pimple
Hugo Hamon
 
PDF
Design Patterns in PHP5
Wildan Maulana
 
PDF
Dependency Injection with PHP and PHP 5.3
Fabien Potencier
 
Lithium: The Framework for People Who Hate Frameworks
Nate Abele
 
Unittests für Dummies
Lars Jankowfsky
 
Corephpcomponentpresentation 1211425966721657-8
PrinceGuru MS
 
Adding Dependency Injection to Legacy Applications
Sam Hennessy
 
The Zen of Lithium
Nate Abele
 
Dependency injection - phpday 2010
Fabien Potencier
 
Command Bus To Awesome Town
Ross Tuck
 
The State of Lithium
Nate Abele
 
Perforce Object and Record Model
Perforce
 
Models and Service Layers, Hemoglobin and Hobgoblins
Ross Tuck
 
R57shell
ady36
 
jQuery secrets
Bastian Feder
 
Smelling your code
Raju Mazumder
 
Lithium: The Framework for People Who Hate Frameworks, Tokyo Edition
Nate Abele
 
Php unit the-mostunknownparts
Bastian Feder
 
PHP Data Objects
Wez Furlong
 
Design Patterns avec PHP 5.3, Symfony et Pimple
Hugo Hamon
 
Design Patterns in PHP5
Wildan Maulana
 
Dependency Injection with PHP and PHP 5.3
Fabien Potencier
 

Viewers also liked (20)

PDF
chapters
Chandan Chaurasia
 
ODP
IPC 2013 - High Performance PHP with HipHop
Steve Kamerman
 
PDF
PHP Unit y TDD
Emergya
 
PPTX
Automated php unit testing in drupal 8
Jay Friendly
 
PPTX
PHPUnit with CakePHP and Yii
madhavi Ghadge
 
PPTX
PHPUnit: from zero to hero
Jeremy Cook
 
PDF
Automated Testing in WordPress, Really?!
Ptah Dunbar
 
PDF
CV TEC. ELECT DELMER
Delmer Cordova Sanchez
 
PDF
3 questions you need to ask about your brand
114iiminternship
 
PDF
Curso de Posicionamiento y Marketing de buscadores: SEO, SEM y Analítica
IEBSchool
 
DOC
Moción instituciona lcarril de orozco febrero 2016
Grupo PP Ayuntamiento de Málaga
 
PDF
Ende, michael jim boton y lucas el maquinista204pags.
Cuentos Universales
 
PDF
AJS direct mail piece
Nichole L. Reber
 
PPTX
ORGANOS DE LOS SENTIDOS
Profe Juan Carlos Sechague
 
PDF
IPL Brochure
Chris Smith
 
PDF
Informe público barómetro marca ciudad 2011
Visión Humana
 
PPT
Ramón Cabanillas
blogpousadas
 
PDF
dgaweb
David Veliz
 
IPC 2013 - High Performance PHP with HipHop
Steve Kamerman
 
PHP Unit y TDD
Emergya
 
Automated php unit testing in drupal 8
Jay Friendly
 
PHPUnit with CakePHP and Yii
madhavi Ghadge
 
PHPUnit: from zero to hero
Jeremy Cook
 
Automated Testing in WordPress, Really?!
Ptah Dunbar
 
CV TEC. ELECT DELMER
Delmer Cordova Sanchez
 
3 questions you need to ask about your brand
114iiminternship
 
Curso de Posicionamiento y Marketing de buscadores: SEO, SEM y Analítica
IEBSchool
 
Moción instituciona lcarril de orozco febrero 2016
Grupo PP Ayuntamiento de Málaga
 
Ende, michael jim boton y lucas el maquinista204pags.
Cuentos Universales
 
AJS direct mail piece
Nichole L. Reber
 
ORGANOS DE LOS SENTIDOS
Profe Juan Carlos Sechague
 
IPL Brochure
Chris Smith
 
Informe público barómetro marca ciudad 2011
Visión Humana
 
Ramón Cabanillas
blogpousadas
 
dgaweb
David Veliz
 
Ad

Similar to PhpUnit - The most unknown Parts (20)

PDF
international PHP2011_Bastian Feder_The most unknown Parts of PHPUnit
smueller_sandsmedia
 
PDF
Fighting Fear-Driven-Development With PHPUnit
James Fuller
 
KEY
PHPUnit testing to Zend_Test
Michelangelo van Dam
 
PDF
PHPunit and you
markstory
 
PPT
Unit testing
davidahaskins
 
PDF
Introduction to Unit Testing with PHPUnit
Michelangelo van Dam
 
PDF
Unit testing with PHPUnit
ferca_sl
 
KEY
Php Unit With Zend Framework Zendcon09
Michelangelo van Dam
 
PPTX
Test in action week 2
Yi-Huan Chan
 
PPTX
Test in action week 4
Yi-Huan Chan
 
PPT
PHP Unit Testing
Tagged Social
 
KEY
Developer testing 101: Become a Testing Fanatic
LB Denker
 
PDF
Leveling Up With Unit Testing - LonghornPHP 2022
Mark Niebergall
 
PDF
Getting started with TDD - Confoo 2014
Eric Hogue
 
PDF
Create, test, secure, repeat
Michelangelo van Dam
 
PPT
Unit Testing using PHPUnit
varuntaliyan
 
PDF
Test your code like a pro - PHPUnit in practice
Sebastian Marek
 
PPTX
Php unit
Simona-Elena Stanescu
 
PPTX
Unit Testng with PHP Unit - A Step by Step Training
Ram Awadh Prasad, PMP
 
PPTX
Getting started-php unit
mfrost503
 
international PHP2011_Bastian Feder_The most unknown Parts of PHPUnit
smueller_sandsmedia
 
Fighting Fear-Driven-Development With PHPUnit
James Fuller
 
PHPUnit testing to Zend_Test
Michelangelo van Dam
 
PHPunit and you
markstory
 
Unit testing
davidahaskins
 
Introduction to Unit Testing with PHPUnit
Michelangelo van Dam
 
Unit testing with PHPUnit
ferca_sl
 
Php Unit With Zend Framework Zendcon09
Michelangelo van Dam
 
Test in action week 2
Yi-Huan Chan
 
Test in action week 4
Yi-Huan Chan
 
PHP Unit Testing
Tagged Social
 
Developer testing 101: Become a Testing Fanatic
LB Denker
 
Leveling Up With Unit Testing - LonghornPHP 2022
Mark Niebergall
 
Getting started with TDD - Confoo 2014
Eric Hogue
 
Create, test, secure, repeat
Michelangelo van Dam
 
Unit Testing using PHPUnit
varuntaliyan
 
Test your code like a pro - PHPUnit in practice
Sebastian Marek
 
Unit Testng with PHP Unit - A Step by Step Training
Ram Awadh Prasad, PMP
 
Getting started-php unit
mfrost503
 
Ad

More from Bastian Feder (17)

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

Recently uploaded (20)

PDF
ARAL-Orientation_Morning-Session_Day-11.pdf
JoelVilloso1
 
PPTX
How to Configure Prepayments in Odoo 18 Sales
Celine George
 
PPTX
Unit 2 COMMERCIAL BANKING, Corporate banking.pptx
AnubalaSuresh1
 
PDF
CHILD RIGHTS AND PROTECTION QUESTION BANK
Dr Raja Mohammed T
 
PPTX
How to Create Rental Orders in Odoo 18 Rental
Celine George
 
PPTX
How to Configure Lost Reasons in Odoo 18 CRM
Celine George
 
PPTX
How to Manage Large Scrollbar in Odoo 18 POS
Celine George
 
PPSX
Health Planning in india - Unit 03 - CHN 2 - GNM 3RD YEAR.ppsx
Priyanshu Anand
 
PPTX
HYDROCEPHALUS: NURSING MANAGEMENT .pptx
PRADEEP ABOTHU
 
PPTX
Growth and development and milestones, factors
BHUVANESHWARI BADIGER
 
PPTX
Soil and agriculture microbiology .pptx
Keerthana Ramesh
 
PDF
Zoology (Animal Physiology) practical Manual
raviralanaresh2
 
PPTX
ASRB NET 2023 PREVIOUS YEAR QUESTION PAPER GENETICS AND PLANT BREEDING BY SAT...
Krashi Coaching
 
PDF
LAW OF CONTRACT (5 YEAR LLB & UNITARY LLB )- MODULE - 1.& 2 - LEARN THROUGH P...
APARNA T SHAIL KUMAR
 
PPTX
Quarter1-English3-W4-Identifying Elements of the Story
FLORRACHELSANTOS
 
PPTX
Views on Education of Indian Thinkers J.Krishnamurthy..pptx
ShrutiMahanta1
 
PPT
Talk on Critical Theory, Part II, Philosophy of Social Sciences
Soraj Hongladarom
 
PDF
Generative AI: it's STILL not a robot (CIJ Summer 2025)
Paul Bradshaw
 
PDF
BÀI TẬP BỔ TRỢ THEO LESSON TIẾNG ANH - I-LEARN SMART WORLD 7 - CẢ NĂM - CÓ ĐÁ...
Nguyen Thanh Tu Collection
 
PPTX
A PPT on Alfred Lord Tennyson's Ulysses.
Beena E S
 
ARAL-Orientation_Morning-Session_Day-11.pdf
JoelVilloso1
 
How to Configure Prepayments in Odoo 18 Sales
Celine George
 
Unit 2 COMMERCIAL BANKING, Corporate banking.pptx
AnubalaSuresh1
 
CHILD RIGHTS AND PROTECTION QUESTION BANK
Dr Raja Mohammed T
 
How to Create Rental Orders in Odoo 18 Rental
Celine George
 
How to Configure Lost Reasons in Odoo 18 CRM
Celine George
 
How to Manage Large Scrollbar in Odoo 18 POS
Celine George
 
Health Planning in india - Unit 03 - CHN 2 - GNM 3RD YEAR.ppsx
Priyanshu Anand
 
HYDROCEPHALUS: NURSING MANAGEMENT .pptx
PRADEEP ABOTHU
 
Growth and development and milestones, factors
BHUVANESHWARI BADIGER
 
Soil and agriculture microbiology .pptx
Keerthana Ramesh
 
Zoology (Animal Physiology) practical Manual
raviralanaresh2
 
ASRB NET 2023 PREVIOUS YEAR QUESTION PAPER GENETICS AND PLANT BREEDING BY SAT...
Krashi Coaching
 
LAW OF CONTRACT (5 YEAR LLB & UNITARY LLB )- MODULE - 1.& 2 - LEARN THROUGH P...
APARNA T SHAIL KUMAR
 
Quarter1-English3-W4-Identifying Elements of the Story
FLORRACHELSANTOS
 
Views on Education of Indian Thinkers J.Krishnamurthy..pptx
ShrutiMahanta1
 
Talk on Critical Theory, Part II, Philosophy of Social Sciences
Soraj Hongladarom
 
Generative AI: it's STILL not a robot (CIJ Summer 2025)
Paul Bradshaw
 
BÀI TẬP BỔ TRỢ THEO LESSON TIẾNG ANH - I-LEARN SMART WORLD 7 - CẢ NĂM - CÓ ĐÁ...
Nguyen Thanh Tu Collection
 
A PPT on Alfred Lord Tennyson's Ulysses.
Beena E S
 

PhpUnit - The most unknown Parts

  • 1. The most unknown parts of PHPUnit Bastian Feder Confoo 2011 Montreal [email protected] 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: [email protected]
  • 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