The most unknown parts of PHPUnit




Bastian Feder
lapistano@php.net                   19th September 2010
Agenda

●   PHPUnit on the command line
●   Assertions
●   Annotations
●   Special tests
… on the command line

●    -- testdox[-(html|text)]
     generates a especially styled test report.
●    -- filter <patte...
… on the command line (continiued)

●   -- stop-on-failure
    stops the testrun on the first recognized failure.
●   -- c...
Assertions

  „In computer programming, an assertion is a
  predicate (for example a true–false statement)
  placed in a p...
Assertions (continiued)

    assertContains(), assertContainsOnly()

●   Cameleon within the asserts, handles
        –   ...
Assertions (continiued)

●   assertXMLFileEqualsXMLFile()
●   assertXMLStringEqualsXMLFile()
●   assertXMLStringEqualsXMLS...
Assertions (continiued)


          $ phpunit XmlFileEqualsXmlFileTest.php
          PHPUnit 3.4.15 by Sebastian Bergmann....
Assertions (continiued)

    assertObjectHasAttribute()
    assertClassHasAttribute()

●   Overcomes visibilty by using Re...
Assertions (continiued)

    assertAttribute*()

●   Asserts the content of a class attribute
    regardless its' visibili...
Assertions (continiued)

  assertType()


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

   $this-...
Assertions (continiued)

    assertSelectEquals(), assertSelectCount()

●   Assert the presence, absence, or count of
    ...
Assertions (continiued)

  assertSelectRegExp()


   $xml = = '
        <items version="1.0">
          <persons>
        ...
Assertions (continiued)

    assertThat()

●   Evaluates constraints to build complex
    assertions.

    $this->assertTh...
Inverted Assertions

    Mostly every assertion has an inverted sibling.
●   assertNotContains()
●   assertNotThat()
●   a...
Annotations

  „In software programming, annotations are
  used mainly for the purpose of expanding code
  documentation a...
Annotations (continiued)

     @covers, @group

 /**
  * @covers myClass:run
  * @group exceptions
  * @group Trac-123
  *...
Annotations (continiued)

    @depends

public function testIsApcAvailable() {

     if ( ! extension_loaded( 'apc' ) ) {
...
Special tests

  Testing exceptions
      –   @expectedException



  /**
   * @expectedException InvalidArgumentException...
Special tests (continued)

     Testing exceptions
        –   SetExpectedException( 'Exception' )



 public function tes...
Special tests (continued)

     Testing exceptions
        –   try/catch


 public function testInvalidArgumentException()...
Special Tests (continiued)

  returnCallback()

public function callbackGetObject($name, $className = '')
{
    retrun (st...
Special Tests (continiued)

  onConsecutiveCalls()

[…]

$application = $this->getMock('FluentDOM');
$application
    ->ex...
Special Tests (continiued)

    implecit integration tests


public function testGet() {

     $mock = $this->getMock(
   ...
Slides'n contact

●   Please comment the talk on joind.in
         http://joind.in/1901
●   Slides
         http://slidesh...
License

   This set of slides and the source code included
    in the download package is licensed under the

        Cr...
Upcoming SlideShare
Loading in...5
×

Php unit the-mostunknownparts

3,287

Published on

A lot of people using PHPunit for testing their source code. While I was observing my team
I recognized most of them are only using the standard assertions like 'assertEquals()' or 'assertTrue()' and are complaining about how hard it is to test the code even when the tests are written first. This talk is about all the stuff not used on a daily basis. It shows you some nice features of PHPUnit and how to use them for your benefit.

Published in: Technology
0 Comments
2 Likes
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total Views
3,287
On Slideshare
0
From Embeds
0
Number of Embeds
0
Actions
Shares
0
Downloads
0
Comments
0
Likes
2
Embeds 0
No embeds

No notes for slide

Transcript of "Php unit the-mostunknownparts"

  1. 1. The most unknown parts of PHPUnit Bastian Feder lapistano@php.net 19th September 2010
  2. 2. Agenda ● PHPUnit on the command line ● Assertions ● Annotations ● Special tests
  3. 3. … on the command line ● -- testdox[-(html|text)] generates a especially styled test report. ● -- filter <pattern> filters which testsuite to run. $ phpunit --filter Handler --testdox . PHPUnit 3.4.15 by Sebastian Bergmann. FluentDOMCore [x] Get handler FluentDOMHandler [x] Insert nodes after [x] Insert nodes before [x] Append children [x] Insert children before
  4. 4. … on the command line (continiued) ● -- 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)
  5. 5. 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)
  6. 6. Assertions (continiued) 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));
  7. 7. Assertions (continiued) ● assertXMLFileEqualsXMLFile() ● assertXMLStringEqualsXMLFile() ● assertXMLStringEqualsXMLString() $this->assertXMLFileEqualsXMLFile( '/path/to/Expected.xml', '/path/to/Fixture.xml' );
  8. 8. Assertions (continiued) $ 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
  9. 9. Assertions (continiued) 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' );
  10. 10. Assertions (continiued) 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 );
  11. 11. Assertions (continiued) 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' );
  12. 12. Assertions (continiued) 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 );
  13. 13. Assertions (continiued) 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);
  14. 14. Assertions (continiued) assertThat() ● Evaluates constraints to build complex assertions. $this->assertThat( $expected, $ths->logicalAnd( $this->isInstanceOf('tire'), $this->logicalNot( $this->identicalTo($myFrontTire) ) ) );
  15. 15. Inverted Assertions Mostly every assertion has an inverted sibling. ● assertNotContains() ● assertNotThat() ● assertAttributeNotSame() ● […]
  16. 16. 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 )
  17. 17. Annotations (continiued) @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 ) { } }
  18. 18. Annotations (continiued) @depends public function testIsApcAvailable() { if ( ! extension_loaded( 'apc' ) ) { $this->markTestSkipped( 'Required APC not available' ); } } /** * @depend testIsApcAvailable */ public function testGetFileFromAPC () { }
  19. 19. Special tests Testing exceptions – @expectedException /** * @expectedException InvalidArgumentException */ public function testInvalidArgumentException() { $obj = new myClass(); $obj->run('invalidArgument'); }
  20. 20. Special tests (continued) Testing exceptions – SetExpectedException( 'Exception' ) public function testInvalidArgumentException() { $this->setExpectedException('InvalidArgumentException ') $obj = new myClass(); $obj->run('invalidArgument'); }
  21. 21. Special tests (continued) Testing exceptions – try/catch public function testInvalidArgumentException() { $obj = new myClass(); try{ $obj->run( 'invalidArgument' ); $this->fail('Expected exception not thrown.'); } catch ( InvalidArgumentException $e ) { } }
  22. 22. Special Tests (continiued) returnCallback() 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') ) ); […]
  23. 23. Special Tests (continiued) onConsecutiveCalls() […] $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) ) ); […]
  24. 24. Special Tests (continiued) implecit integration tests public function testGet() { $mock = $this->getMock( 'myAbstraction', array( 'method' ) ); $mock ->expected( $this->once() ) ->method( 'methoSd' ) ->will( $this->returnValue( 'return' ); }
  25. 25. Slides'n contact ● Please comment the talk on joind.in http://joind.in/1901 ● Slides http://slideshare.net/lapistano ● Email: lapistano@php.net
  26. 26. 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

×