SlideShare ist ein Scribd-Unternehmen logo
1 von 32
phpunit
How not to get roundkicked by Chuck Norris
Unit testing




   • wat is unit testen?
   • phpunit?
   • code coverage?
testcase (1)

Foo.php
 <?php
 class foo
 {
   public function baz() {
     return 1;
   }
 }




FooTest.php:
 <?php
 class fooTest extends PHPUnit_Framework_TestCase
 {
   public function testBlahBlah() {
     $foo = new Foo();
     $this->assertEquals($foo->baz(), 1);
   }
 }
testcase (2)

Foo.php
 <?php
 class foo
 {
   public function baz() {
     return 1;
   }
 }




FooTest.php:
 include_once "foo.php";

 class fooTest extends PHPUnit_Framework_TestCase
 {
         public function testBlahBlah() {
                 $foo = new Foo();
                 $this->assertEquals($foo->baz(), 1);
         }
 }
testcase (3)
testcase (4)

Foo.php
                                               FooTest.php:
   <?php
   class foo
   {                                            <?php
           public function baz() {
                   return 1;                    include_once "foo.php";
           }
                                                class fooTest extends PHPUnit_Framework_TestCase
           public function isOdd($number) {     {
                   if (($number & 1) == 1) {            public function testBlahBlah() {
                            return true;                        $foo = new Foo();
                   } else {                                     $this->assertEquals($foo->baz(), 1);
                            return false;               }
                   }
           }                                            public function testIsOdd() {
   }                                                            $foo = new Foo();
                                                                $this->assertTrue($foo->isOdd(1));
                                                        }
                                                }
testcase (5)
testcase (6)
testcase (7)


FooTest.php:
 <?php

 include_once "foo.php";

 class fooTest extends PHPUnit_Framework_TestCase
 {
         public function testBlahBlah() {
                 $foo = new Foo();
                 $this->assertEquals($foo->baz(), 1);
         }

          public function testIsOdd() {
                  $foo = new Foo();
                  $this->assertTrue($foo->isOdd(1));
         }

         public function testDoesIsOddReturnFalseWhenAnEvenDigitIsGiven {
                  $foo = new Foo();
                  $this->assertFalse($foo->isOdd(2));
          }
 }
testcase (8)
PHPUnit chapters




  • setUp(), tearDown()
  • @depends
  • @dataproviders
  • @exception testing
  • mocking & stubbing
setUp(), tearDown() (1)




 <?php
 class fooTest extends PHPUnit_Framework_TestCase
 {
   public function testBlahBlah() {
     $foo = new Bar();
     ....
   }
   public function testBlah() {
     $foo = new Bar();
     ....
   }

 }
setUp(), tearDown() (2)


 <?php
 class fooTest extends PHPUnit_Framework_TestCase
 {
   public setUp() {
     $this->_foo = new Bar();
   }

     public tearDown() {
       unset($this->_foo);
     }

     public function testBlahBlah() {
       ....
     }
     public function testBlah() {
       ....
     }

 }
@depends (1)



 <?php
 class fooTest extends PHPUnit_Framework_TestCase
 {

     public function testFoo() {
       ....
     }

     /**
       * @depends testFoo
       */
     public function testBar() {
        ....
     }

 }
@dataprovider (1)




 <?php
 class fooTest extends PHPUnit_Framework_TestCase
 {

     public function testCount() {
       $foo = new Foo();
       $this->assertEquals($foo->add(1, 2), 3);
       $this->assertEquals($foo->add(10,-4), 6);
       $this->assertEquals($foo->add(4, 6), 10);
       ...
     }

 }
@dataprovider (2)


 <?php
 class fooTest extends PHPUnit_Framework_TestCase
 {

     /**
       * @dataprovider countProvider
       */
     public function testCount($a, $b, $c) {
        $foo = new Foo();
        $this->assertEquals($foo->add($a, $b), $c);
     }

     public function countProvider() {
       return array(
          array(1, 2, 3),
          array(10, -4, 6),
          array(4, 6, 10)
       );
     }

 }
@expectedException (1)



 <?php
 class fooTest extends PHPUnit_Framework_TestCase
 {

     public function testCount() {
       $foo = new Foo();
       try {
         $foo->functionWithException();
         $this->fail(“An exception should have occurred”);
       } catch (Exception $e) {

         }
     }

 }
@expectedException (2)




 <?php
 class fooTest extends PHPUnit_Framework_TestCase
 {

     /**
       * @expectedException Exception
       */
     public function testCount() {
        $foo = new Foo();
        $foo->functionWithException();
     }

 }
Mocking & Stubbing (1)


 <?php

  class MyMailer {
        protected $_from;
        protected $_body;
        protected $_subject;

         function setFrom($from) {
                 $this->_from = $from;
         }

         .......

         function mail(array $to) {
                 $count = 0;
                 foreach ($to as $recipient) {

                 }
                         if ($this->_mail($recipient)) $count++;
                                                                    Isolated
                 return $count;
         }

         protected function _mail($to) {
                 return mail($to, $this->_subject, $this->_body);
         }
  }
Mocking & Stubbing (2)


 <?php

     include_once "mail.php";

 class Mock_MyMailer extends MyMailer {
         protected function _mail($to) {
                 return true;
         }
 }

 class mailTest extends PHPUnit_Framework_TestCase
 {
         ...

           public function testMail() {
                   $mailer = new Mock_MyMailer();
                   $mailer->setSubject("blaat");
                   $mailer->setFrom("jthijssen@example.com");
                   $mailer->setBody("meeh");

                   $to = array("aap@example.com", "blaat@example.com", "all@example.com");
                   $this->assertEquals($mailer->mail($to), 3);
           }
 }
Mocking & Stubbing (3)



 <?php

 include_once "mail.php";

 class mailTest extends PHPUnit_Framework_TestCase
 {
         ...

         public function testMail() {

                 $mailer = new MyMailer();
                 $mailer->setSubject("blaat");
                 $mailer->setFrom("jthijssen@example.com");
                 $mailer->setBody("meeh");

                 $to = array("aap@example.com", "blaat@example.com", "all@example.com");
                 $this->assertEquals($mailer->mail($to), 3);
         }
 }
Mocking & Stubbing (4)




 <?php

 class mailTest extends PHPUnit_Framework_TestCase
 {
         public function testMail() {
                 $stub = $this->getMockBuilder('MyMailer', array('_mail'))->getMock();
                 $stub->expects($this->any())
                      ->method('_mail')
                      ->will($this->returnValue(true));

                 $stub->setSubject("blaat");
                 $stub->setFrom("jthijssen@example.com");
                 $stub->setBody("meeh");

                 $to = array("aap@example.com", "blaat@example.com", "all@example.com");
                 $this->assertEquals($stub->mail($to), 3);
         }
 }
Difficult cases (1)




   public function getItem($id) {
     $client = new Zend_Http_Client();
     $client->setUri(‘http://my.api’);
     $client->setParameterPost(‘ID’,$id);
     $client->setMethod(Zend-Http_Client::POST);
     $request = $client->request();

       $item = $request->getBody();
       $item = strtolower($item);
       return $item;
   }




∂ TESTABLE?
Difficult cases (2)




   public function __construct() {
       $this->_adapter = new Zend_Http_Client_Adapter_Socket();
   }

   public function getItem($id) {
     $client = new Zend_Http_Client();
     $client->setConfig(array(‘adapter’ => $this->getAdapter()));
     $client->setUri(‘http://my.api’);
     $client->setParameterPost(‘ID’,$id);
     $client->setMethod(Zend-Http_Client::POST);
     $request = $client->request();

       $item = $request->getBody();
       $item = strtolower($item);
       return $item;
   }




∂ “DECOUPLE” ADAPTER
Difficult cases (3)




   function testGetItem() {
     $adapter = new Zend_Http_Client_Adapter_Test();
     $adapter->setResponse(“HTTP/1.1 200 OKrnrnBLAAT”);
     $adapter->addResponse(“HTTP/1.1 200 OKrnrnAAP”);

       $foo = new Foo();
       $foo->setAdapter($adapter);
       $this->assertEquals($foo->getItem(1), ‘blaat’);
       $this->assertEquals($foo->getItem(2), ‘aap’);
   }




∂ IT’S TESTABLE AGAIN
Difficult cases (4)




    Gebruik “dependency injection” ipv
    “tight coupling”.
Dependency Injection (1)




   public function pay(Article $article) {
     $psp = new PaymentProvider();
     $psp->setAmount($article->getAmount());
     return $psp->pay();
   }




∂ THIGHT COUPLING AGAIN
Dependency Injection (2)




  public function setPaymentProvider(PaymentProvider $psp) {
    $this->_psp = $psp;
  }

  public function getPaymentProvider() {
    return $this->_psp;
  }

  public function pay(Article $article) {
    $psp = $this->getPaymentProvider();
    $psp->setAmount($article->getAmount());
    return $psp->pay();
  }




∂ DECOUPLE PAYMENT PROVIDER
Dependency Injection (3)




 public function testPayAccepted() {
   $stub = $this->getMockBuilder(‘paymentprovider’, array(‘pay’))->getMock();

     $stub->expects($this->any())
          ->method(‘pay’)
          ->will($this->returnValue(true));

     $article = new Article();
     $article->setAmount(15);

     $foo = new Foo();
     $foo->setPaymentProvider($stub);
     $this->assertTrue($foo->pay($article));

     $this->assertEquals($user->getAmount(), 85);
 }




∂ TESTABLE *AND* EXTENDABLE
Dependency Injection (4)




  public function testPayFailed() {
    $stub = $this->getMockBuilder(‘paymentprovider’, array(‘pay’))->getMock();

    $stub->expects($this->any())
         ->method(‘pay’)
         ->will($this->returnValue(false));

    $article = new Article();
    $article->setAmount(15);

    $foo = new Foo();
    $foo->setPaymentProvider($stub);
    $this->assertFalse($foo->pay($article));

  $this->assertEquals($user->getAmount(), 100);
  }




∂ TESTABLE *AND* EXTENDABLE
Workshop



   • Login op php5dev02
   • directory: workshop
   • http://workshop.<username>.dev/
      tests/coverage

   • cd tests
   • ./runtest.sh
∂ FOLLOW INSTRUCTIONS
∂ THANK YOU FOR YOUR ATTENTION

Weitere ähnliche Inhalte

Was ist angesagt?

Good Evils In Perl (Yapc Asia)
Good Evils In Perl (Yapc Asia)Good Evils In Perl (Yapc Asia)
Good Evils In Perl (Yapc Asia)
Kang-min Liu
 
OSDC.TW - Gutscript for PHP haters
OSDC.TW - Gutscript for PHP hatersOSDC.TW - Gutscript for PHP haters
OSDC.TW - Gutscript for PHP haters
Lin Yo-An
 
Unit testing with PHPUnit
Unit testing with PHPUnitUnit testing with PHPUnit
Unit testing with PHPUnit
ferca_sl
 

Was ist angesagt? (20)

PHP Enums - PHPCon Japan 2021
PHP Enums - PHPCon Japan 2021PHP Enums - PHPCon Japan 2021
PHP Enums - PHPCon Japan 2021
 
Melhorando sua API com DSLs
Melhorando sua API com DSLsMelhorando sua API com DSLs
Melhorando sua API com DSLs
 
What's new in PHP 8.0?
What's new in PHP 8.0?What's new in PHP 8.0?
What's new in PHP 8.0?
 
IPC2010SE Doctrine2 Enterprise Persistence Layer for PHP
IPC2010SE Doctrine2 Enterprise Persistence Layer for PHPIPC2010SE Doctrine2 Enterprise Persistence Layer for PHP
IPC2010SE Doctrine2 Enterprise Persistence Layer for PHP
 
Mirror, mirror on the wall: Building a new PHP reflection library (DPC 2016)
Mirror, mirror on the wall: Building a new PHP reflection library (DPC 2016)Mirror, mirror on the wall: Building a new PHP reflection library (DPC 2016)
Mirror, mirror on the wall: Building a new PHP reflection library (DPC 2016)
 
関西PHP勉強会 php5.4つまみぐい
関西PHP勉強会 php5.4つまみぐい関西PHP勉強会 php5.4つまみぐい
関西PHP勉強会 php5.4つまみぐい
 
PHPUnit best practices presentation
PHPUnit best practices presentationPHPUnit best practices presentation
PHPUnit best practices presentation
 
A Functional Guide to Cat Herding with PHP Generators
A Functional Guide to Cat Herding with PHP GeneratorsA Functional Guide to Cat Herding with PHP Generators
A Functional Guide to Cat Herding with PHP Generators
 
Functional Structures in PHP
Functional Structures in PHPFunctional Structures in PHP
Functional Structures in PHP
 
Just-In-Time Compiler in PHP 8
Just-In-Time Compiler in PHP 8Just-In-Time Compiler in PHP 8
Just-In-Time Compiler in PHP 8
 
Zend Certification Preparation Tutorial
Zend Certification Preparation TutorialZend Certification Preparation Tutorial
Zend Certification Preparation Tutorial
 
A Functional Guide to Cat Herding with PHP Generators
A Functional Guide to Cat Herding with PHP GeneratorsA Functional Guide to Cat Herding with PHP Generators
A Functional Guide to Cat Herding with PHP Generators
 
DRYing to Monad in Java8
DRYing to Monad in Java8DRYing to Monad in Java8
DRYing to Monad in Java8
 
Good Evils In Perl (Yapc Asia)
Good Evils In Perl (Yapc Asia)Good Evils In Perl (Yapc Asia)
Good Evils In Perl (Yapc Asia)
 
PHP7 is coming
PHP7 is comingPHP7 is coming
PHP7 is coming
 
Memory Manglement in Raku
Memory Manglement in RakuMemory Manglement in Raku
Memory Manglement in Raku
 
Functions in PHP
Functions in PHPFunctions in PHP
Functions in PHP
 
OSDC.TW - Gutscript for PHP haters
OSDC.TW - Gutscript for PHP hatersOSDC.TW - Gutscript for PHP haters
OSDC.TW - Gutscript for PHP haters
 
Unit testing with PHPUnit
Unit testing with PHPUnitUnit testing with PHPUnit
Unit testing with PHPUnit
 
Diving into HHVM Extensions (PHPNW Conference 2015)
Diving into HHVM Extensions (PHPNW Conference 2015)Diving into HHVM Extensions (PHPNW Conference 2015)
Diving into HHVM Extensions (PHPNW Conference 2015)
 

Andere mochten auch

Puppet for dummies - PHPBenelux UG edition
Puppet for dummies - PHPBenelux UG editionPuppet for dummies - PHPBenelux UG edition
Puppet for dummies - PHPBenelux UG edition
Joshua Thijssen
 
Alice & bob public key cryptography 101 - uncon dpc
Alice & bob  public key cryptography 101 - uncon dpcAlice & bob  public key cryptography 101 - uncon dpc
Alice & bob public key cryptography 101 - uncon dpc
Joshua Thijssen
 
Deploying and maintaining your software with RPM/APT
Deploying and maintaining your software with RPM/APTDeploying and maintaining your software with RPM/APT
Deploying and maintaining your software with RPM/APT
Joshua Thijssen
 
15 protips for mysql users pfz
15 protips for mysql users   pfz15 protips for mysql users   pfz
15 protips for mysql users pfz
Joshua Thijssen
 
Alice & bob public key cryptography 101
Alice & bob  public key cryptography 101Alice & bob  public key cryptography 101
Alice & bob public key cryptography 101
Joshua Thijssen
 
Alice & bob public key cryptography 101
Alice & bob  public key cryptography 101Alice & bob  public key cryptography 101
Alice & bob public key cryptography 101
Joshua Thijssen
 
Unix command-line tools
Unix command-line toolsUnix command-line tools
Unix command-line tools
Eric Wilson
 

Andere mochten auch (18)

Moved 301
Moved 301Moved 301
Moved 301
 
Puppet for dummies - PHPBenelux UG edition
Puppet for dummies - PHPBenelux UG editionPuppet for dummies - PHPBenelux UG edition
Puppet for dummies - PHPBenelux UG edition
 
Representation state transfer and some other important stuff
Representation state transfer and some other important stuffRepresentation state transfer and some other important stuff
Representation state transfer and some other important stuff
 
15 protips for mysql users
15 protips for mysql users15 protips for mysql users
15 protips for mysql users
 
Alice & bob public key cryptography 101 - uncon dpc
Alice & bob  public key cryptography 101 - uncon dpcAlice & bob  public key cryptography 101 - uncon dpc
Alice & bob public key cryptography 101 - uncon dpc
 
Deploying and maintaining your software with RPM/APT
Deploying and maintaining your software with RPM/APTDeploying and maintaining your software with RPM/APT
Deploying and maintaining your software with RPM/APT
 
PFZ WorkshopDay Linux - Basic
PFZ WorkshopDay Linux - BasicPFZ WorkshopDay Linux - Basic
PFZ WorkshopDay Linux - Basic
 
PFZ WorkshopDay Linux - Advanced
PFZ WorkshopDay Linux - AdvancedPFZ WorkshopDay Linux - Advanced
PFZ WorkshopDay Linux - Advanced
 
15 protips for mysql users pfz
15 protips for mysql users   pfz15 protips for mysql users   pfz
15 protips for mysql users pfz
 
Alice & bob public key cryptography 101
Alice & bob  public key cryptography 101Alice & bob  public key cryptography 101
Alice & bob public key cryptography 101
 
Cipher block modes
Cipher block modesCipher block modes
Cipher block modes
 
Awk programming
Awk programming Awk programming
Awk programming
 
Czzawk
CzzawkCzzawk
Czzawk
 
Alice & bob public key cryptography 101
Alice & bob  public key cryptography 101Alice & bob  public key cryptography 101
Alice & bob public key cryptography 101
 
Naive Bayes
Naive Bayes Naive Bayes
Naive Bayes
 
Puppet for dummies - ZendCon 2011 Edition
Puppet for dummies - ZendCon 2011 EditionPuppet for dummies - ZendCon 2011 Edition
Puppet for dummies - ZendCon 2011 Edition
 
Unix command-line tools
Unix command-line toolsUnix command-line tools
Unix command-line tools
 
Sed & awk the dynamic duo
Sed & awk   the dynamic duoSed & awk   the dynamic duo
Sed & awk the dynamic duo
 

Ähnlich wie Workshop unittesting

Mocking Dependencies in PHPUnit
Mocking Dependencies in PHPUnitMocking Dependencies in PHPUnit
Mocking Dependencies in PHPUnit
mfrost503
 
SPL: The Missing Link in Development
SPL: The Missing Link in DevelopmentSPL: The Missing Link in Development
SPL: The Missing Link in Development
jsmith92
 
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
 
Object Oriented Programming with PHP 5 - More OOP
Object Oriented Programming with PHP 5 - More OOPObject Oriented Programming with PHP 5 - More OOP
Object Oriented Programming with PHP 5 - More OOP
Wildan Maulana
 
Jsphp 110312161301-phpapp02
Jsphp 110312161301-phpapp02Jsphp 110312161301-phpapp02
Jsphp 110312161301-phpapp02
Seri Moth
 
PHP 5.3 And PHP 6 A Look Ahead
PHP 5.3 And PHP 6 A Look AheadPHP 5.3 And PHP 6 A Look Ahead
PHP 5.3 And PHP 6 A Look Ahead
thinkphp
 
vfsStream - effective filesystem mocking
vfsStream - effective filesystem mocking vfsStream - effective filesystem mocking
vfsStream - effective filesystem mocking
Sebastian Marek
 

Ähnlich wie Workshop unittesting (20)

The Origin of Lithium
The Origin of LithiumThe Origin of Lithium
The Origin of Lithium
 
Oops in php
Oops in phpOops in php
Oops in php
 
Unit testing with zend framework tek11
Unit testing with zend framework tek11Unit testing with zend framework tek11
Unit testing with zend framework tek11
 
Unit testing with zend framework PHPBenelux
Unit testing with zend framework PHPBeneluxUnit testing with zend framework PHPBenelux
Unit testing with zend framework PHPBenelux
 
Unit testing zend framework apps
Unit testing zend framework appsUnit testing zend framework apps
Unit testing zend framework apps
 
Mocking Dependencies in PHPUnit
Mocking Dependencies in PHPUnitMocking Dependencies in PHPUnit
Mocking Dependencies in PHPUnit
 
SPL: The Missing Link in Development
SPL: The Missing Link in DevelopmentSPL: The Missing Link in Development
SPL: The Missing Link in Development
 
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
 
Object Oriented Programming with PHP 5 - More OOP
Object Oriented Programming with PHP 5 - More OOPObject Oriented Programming with PHP 5 - More OOP
Object Oriented Programming with PHP 5 - More OOP
 
PHPUnit でよりよくテストを書くために
PHPUnit でよりよくテストを書くためにPHPUnit でよりよくテストを書くために
PHPUnit でよりよくテストを書くために
 
Jsphp 110312161301-phpapp02
Jsphp 110312161301-phpapp02Jsphp 110312161301-phpapp02
Jsphp 110312161301-phpapp02
 
PHP 5.4
PHP 5.4PHP 5.4
PHP 5.4
 
ekb.py - Python VS ...
ekb.py - Python VS ...ekb.py - Python VS ...
ekb.py - Python VS ...
 
SOLID PRINCIPLES
SOLID PRINCIPLESSOLID PRINCIPLES
SOLID PRINCIPLES
 
Unittests für Dummies
Unittests für DummiesUnittests für Dummies
Unittests für Dummies
 
TestFest - Respect\Validation 1.0
TestFest - Respect\Validation 1.0TestFest - Respect\Validation 1.0
TestFest - Respect\Validation 1.0
 
You code sucks, let's fix it
You code sucks, let's fix itYou code sucks, let's fix it
You code sucks, let's fix it
 
PHP 5.3 And PHP 6 A Look Ahead
PHP 5.3 And PHP 6 A Look AheadPHP 5.3 And PHP 6 A Look Ahead
PHP 5.3 And PHP 6 A Look Ahead
 
vfsStream - effective filesystem mocking
vfsStream - effective filesystem mocking vfsStream - effective filesystem mocking
vfsStream - effective filesystem mocking
 
Your code sucks, let's fix it - DPC UnCon
Your code sucks, let's fix it - DPC UnConYour code sucks, let's fix it - DPC UnCon
Your code sucks, let's fix it - DPC UnCon
 

Workshop unittesting

  • 1. phpunit How not to get roundkicked by Chuck Norris
  • 2. Unit testing • wat is unit testen? • phpunit? • code coverage?
  • 3. testcase (1) Foo.php <?php class foo { public function baz() { return 1; } } FooTest.php: <?php class fooTest extends PHPUnit_Framework_TestCase { public function testBlahBlah() { $foo = new Foo(); $this->assertEquals($foo->baz(), 1); } }
  • 4. testcase (2) Foo.php <?php class foo { public function baz() { return 1; } } FooTest.php: include_once "foo.php"; class fooTest extends PHPUnit_Framework_TestCase { public function testBlahBlah() { $foo = new Foo(); $this->assertEquals($foo->baz(), 1); } }
  • 6. testcase (4) Foo.php FooTest.php: <?php class foo { <?php public function baz() { return 1; include_once "foo.php"; } class fooTest extends PHPUnit_Framework_TestCase public function isOdd($number) { { if (($number & 1) == 1) { public function testBlahBlah() { return true; $foo = new Foo(); } else { $this->assertEquals($foo->baz(), 1); return false; } } } public function testIsOdd() { } $foo = new Foo(); $this->assertTrue($foo->isOdd(1)); } }
  • 9. testcase (7) FooTest.php: <?php include_once "foo.php"; class fooTest extends PHPUnit_Framework_TestCase { public function testBlahBlah() { $foo = new Foo(); $this->assertEquals($foo->baz(), 1); } public function testIsOdd() { $foo = new Foo(); $this->assertTrue($foo->isOdd(1)); } public function testDoesIsOddReturnFalseWhenAnEvenDigitIsGiven { $foo = new Foo(); $this->assertFalse($foo->isOdd(2)); } }
  • 11. PHPUnit chapters • setUp(), tearDown() • @depends • @dataproviders • @exception testing • mocking & stubbing
  • 12. setUp(), tearDown() (1) <?php class fooTest extends PHPUnit_Framework_TestCase { public function testBlahBlah() { $foo = new Bar(); .... } public function testBlah() { $foo = new Bar(); .... } }
  • 13. setUp(), tearDown() (2) <?php class fooTest extends PHPUnit_Framework_TestCase { public setUp() { $this->_foo = new Bar(); } public tearDown() { unset($this->_foo); } public function testBlahBlah() { .... } public function testBlah() { .... } }
  • 14. @depends (1) <?php class fooTest extends PHPUnit_Framework_TestCase { public function testFoo() { .... } /** * @depends testFoo */ public function testBar() { .... } }
  • 15. @dataprovider (1) <?php class fooTest extends PHPUnit_Framework_TestCase { public function testCount() { $foo = new Foo(); $this->assertEquals($foo->add(1, 2), 3); $this->assertEquals($foo->add(10,-4), 6); $this->assertEquals($foo->add(4, 6), 10); ... } }
  • 16. @dataprovider (2) <?php class fooTest extends PHPUnit_Framework_TestCase { /** * @dataprovider countProvider */ public function testCount($a, $b, $c) { $foo = new Foo(); $this->assertEquals($foo->add($a, $b), $c); } public function countProvider() { return array( array(1, 2, 3), array(10, -4, 6), array(4, 6, 10) ); } }
  • 17. @expectedException (1) <?php class fooTest extends PHPUnit_Framework_TestCase { public function testCount() { $foo = new Foo(); try { $foo->functionWithException(); $this->fail(“An exception should have occurred”); } catch (Exception $e) { } } }
  • 18. @expectedException (2) <?php class fooTest extends PHPUnit_Framework_TestCase { /** * @expectedException Exception */ public function testCount() { $foo = new Foo(); $foo->functionWithException(); } }
  • 19. Mocking & Stubbing (1) <?php class MyMailer { protected $_from; protected $_body; protected $_subject; function setFrom($from) { $this->_from = $from; } ....... function mail(array $to) { $count = 0; foreach ($to as $recipient) { } if ($this->_mail($recipient)) $count++; Isolated return $count; } protected function _mail($to) { return mail($to, $this->_subject, $this->_body); } }
  • 20. Mocking & Stubbing (2) <?php include_once "mail.php"; class Mock_MyMailer extends MyMailer { protected function _mail($to) { return true; } } class mailTest extends PHPUnit_Framework_TestCase { ... public function testMail() { $mailer = new Mock_MyMailer(); $mailer->setSubject("blaat"); $mailer->setFrom("jthijssen@example.com"); $mailer->setBody("meeh"); $to = array("aap@example.com", "blaat@example.com", "all@example.com"); $this->assertEquals($mailer->mail($to), 3); } }
  • 21. Mocking & Stubbing (3) <?php include_once "mail.php"; class mailTest extends PHPUnit_Framework_TestCase { ... public function testMail() { $mailer = new MyMailer(); $mailer->setSubject("blaat"); $mailer->setFrom("jthijssen@example.com"); $mailer->setBody("meeh"); $to = array("aap@example.com", "blaat@example.com", "all@example.com"); $this->assertEquals($mailer->mail($to), 3); } }
  • 22. Mocking & Stubbing (4) <?php class mailTest extends PHPUnit_Framework_TestCase { public function testMail() { $stub = $this->getMockBuilder('MyMailer', array('_mail'))->getMock(); $stub->expects($this->any()) ->method('_mail') ->will($this->returnValue(true)); $stub->setSubject("blaat"); $stub->setFrom("jthijssen@example.com"); $stub->setBody("meeh"); $to = array("aap@example.com", "blaat@example.com", "all@example.com"); $this->assertEquals($stub->mail($to), 3); } }
  • 23. Difficult cases (1) public function getItem($id) { $client = new Zend_Http_Client(); $client->setUri(‘http://my.api’); $client->setParameterPost(‘ID’,$id); $client->setMethod(Zend-Http_Client::POST); $request = $client->request(); $item = $request->getBody(); $item = strtolower($item); return $item; } ∂ TESTABLE?
  • 24. Difficult cases (2) public function __construct() { $this->_adapter = new Zend_Http_Client_Adapter_Socket(); } public function getItem($id) { $client = new Zend_Http_Client(); $client->setConfig(array(‘adapter’ => $this->getAdapter())); $client->setUri(‘http://my.api’); $client->setParameterPost(‘ID’,$id); $client->setMethod(Zend-Http_Client::POST); $request = $client->request(); $item = $request->getBody(); $item = strtolower($item); return $item; } ∂ “DECOUPLE” ADAPTER
  • 25. Difficult cases (3) function testGetItem() { $adapter = new Zend_Http_Client_Adapter_Test(); $adapter->setResponse(“HTTP/1.1 200 OKrnrnBLAAT”); $adapter->addResponse(“HTTP/1.1 200 OKrnrnAAP”); $foo = new Foo(); $foo->setAdapter($adapter); $this->assertEquals($foo->getItem(1), ‘blaat’); $this->assertEquals($foo->getItem(2), ‘aap’); } ∂ IT’S TESTABLE AGAIN
  • 26. Difficult cases (4) Gebruik “dependency injection” ipv “tight coupling”.
  • 27. Dependency Injection (1) public function pay(Article $article) { $psp = new PaymentProvider(); $psp->setAmount($article->getAmount()); return $psp->pay(); } ∂ THIGHT COUPLING AGAIN
  • 28. Dependency Injection (2) public function setPaymentProvider(PaymentProvider $psp) { $this->_psp = $psp; } public function getPaymentProvider() { return $this->_psp; } public function pay(Article $article) { $psp = $this->getPaymentProvider(); $psp->setAmount($article->getAmount()); return $psp->pay(); } ∂ DECOUPLE PAYMENT PROVIDER
  • 29. Dependency Injection (3) public function testPayAccepted() { $stub = $this->getMockBuilder(‘paymentprovider’, array(‘pay’))->getMock(); $stub->expects($this->any()) ->method(‘pay’) ->will($this->returnValue(true)); $article = new Article(); $article->setAmount(15); $foo = new Foo(); $foo->setPaymentProvider($stub); $this->assertTrue($foo->pay($article)); $this->assertEquals($user->getAmount(), 85); } ∂ TESTABLE *AND* EXTENDABLE
  • 30. Dependency Injection (4) public function testPayFailed() { $stub = $this->getMockBuilder(‘paymentprovider’, array(‘pay’))->getMock(); $stub->expects($this->any()) ->method(‘pay’) ->will($this->returnValue(false)); $article = new Article(); $article->setAmount(15); $foo = new Foo(); $foo->setPaymentProvider($stub); $this->assertFalse($foo->pay($article)); $this->assertEquals($user->getAmount(), 100); } ∂ TESTABLE *AND* EXTENDABLE
  • 31. Workshop • Login op php5dev02 • directory: workshop • http://workshop.<username>.dev/ tests/coverage • cd tests • ./runtest.sh ∂ FOLLOW INSTRUCTIONS
  • 32. ∂ THANK YOU FOR YOUR ATTENTION

Hinweis der Redaktion

  1. \n
  2. \n
  3. \n
  4. \n
  5. \n
  6. \n
  7. \n
  8. \n
  9. \n
  10. \n
  11. \n
  12. \n
  13. \n
  14. \n
  15. \n
  16. \n
  17. \n
  18. \n
  19. \n
  20. \n
  21. \n
  22. \n
  23. \n
  24. \n
  25. \n
  26. \n
  27. \n
  28. \n
  29. \n
  30. \n
  31. \n
  32. \n