SlideShare a Scribd company logo
Unit Test Fun: Mock Objects, Fixtures,
Stubs & Dependency Injection

Max Köhler I 02. Dezember 2010




                                         © 2010 Mayflower GmbH
Wer macht UnitTests?



      Unit Test Fun: Mock Objects, Fixtures, Stubs & Dependency Injection I   Mayflower GmbH I 02. Dezember 2010 I 2
Code Coverage?



   Unit Test Fun: Mock Objects, Fixtures, Stubs & Dependency Injection I   Mayflower GmbH I 02. Dezember 2010 I 3
Wer glaubt, dass die Tests
       gut sind?


        Unit Test Fun: Mock Objects, Fixtures, Stubs & Dependency Injection I   Mayflower GmbH I 02. Dezember 2010 I 4
Kann die Qualität
gesteigert werden?
                                                                                                      100%




                                                                              0%
     Unit Test Fun: Mock Objects, Fixtures, Stubs & Dependency Injection I   Mayflower GmbH I 02. Dezember 2010 I 5
Test der kompletten
    Architektur?


     Unit Test Fun: Mock Objects, Fixtures, Stubs & Dependency Injection I   Mayflower GmbH I 02. Dezember 2010 I 6
MVC?
                         Controller




View                                                     Model




       Unit Test Fun: Mock Objects, Fixtures, Stubs & Dependency Injection I   Mayflower GmbH I 02. Dezember 2010 I 7
Wie testet Ihr eure
    Models?


     Unit Test Fun: Mock Objects, Fixtures, Stubs & Dependency Injection I   Mayflower GmbH I 02. Dezember 2010 I 8
Direkter DB-Zugriff?



     Unit Test Fun: Mock Objects, Fixtures, Stubs & Dependency Injection I   Mayflower GmbH I 02. Dezember 2010 I 9
Keine UnitTests!

                                                             STOP




   Unit Test Fun: Mock Objects, Fixtures, Stubs & Dependency Injection I   Mayflower GmbH I 02. Dezember 2010 I 10
Integration Tests!



    Unit Test Fun: Mock Objects, Fixtures, Stubs & Dependency Injection I   Mayflower GmbH I 02. Dezember 2010 I 11
Wie testet Ihr eure
  Controller?


     Unit Test Fun: Mock Objects, Fixtures, Stubs & Dependency Injection I   Mayflower GmbH I 02. Dezember 2010 I 12
Routes, Auth-Mock,
 Session-Mock, ...?


     Unit Test Fun: Mock Objects, Fixtures, Stubs & Dependency Injection I   Mayflower GmbH I 02. Dezember 2010 I 13
Keine UnitTests!

                                                             STOP




   Unit Test Fun: Mock Objects, Fixtures, Stubs & Dependency Injection I   Mayflower GmbH I 02. Dezember 2010 I 14
Was wollen wir testen?



       Unit Test Fun: Mock Objects, Fixtures, Stubs & Dependency Injection I   Mayflower GmbH I 02. Dezember 2010 I 15
Integration                                                     Regression
          Testing                                                            Testing




                                Unit Testing

System - Integration
      Testing
                                                                                          Acceptance
                                                                                               Testing

                       System Testing




                       Unit Test Fun: Mock Objects, Fixtures, Stubs & Dependency Injection I   Mayflower GmbH I 02. Dezember 2010 I 16
The goal of unit testing is
to isolate each part of the
 program and show that
 the individual parts are
                  correct




      Unit Test Fun: Mock Objects, Fixtures, Stubs & Dependency Injection I   Mayflower GmbH I 02. Dezember 2010 I 17
Test Doubles



  Unit Test Fun: Mock Objects, Fixtures, Stubs & Dependency Injection I   Mayflower GmbH I 02. Dezember 2010 I 18
Stubs



Unit Test Fun: Mock Objects, Fixtures, Stubs & Dependency Injection I   Mayflower GmbH I 02. Dezember 2010 I 19
Fake that returns
 canned data...




   Unit Test Fun: Mock Objects, Fixtures, Stubs & Dependency Injection I   Mayflower GmbH I 02. Dezember 2010 I 20
Beispiel für ein Auth-Stub



   $storageData = array(
       'accountId' => 29,
       'username' => 'Hugo',
       'jid'       => 'hugo@example.org');

   $storage = $this->getMock('Zend_Auth_Storage_Session', array('read'));
   $storage->expects($this->any())
           ->method('read')
           ->will($this->returnValue($storageData));

   Zend_Auth::getInstance()->setStorage($storage);

   // ...

   /*
    * Bei jedem Aufruf wird nun das Mock als Storage
    * verwendet und dessen Daten ausgelesen
    */
   $session = Zend_Auth::getInstance()->getIdentity();




                                Unit Test Fun: Mock Objects, Fixtures, Stubs & Dependency Injection I   Mayflower GmbH I 02. Dezember 2010 I 21
Mocks



Unit Test Fun: Mock Objects, Fixtures, Stubs & Dependency Injection I   Mayflower GmbH I 02. Dezember 2010 I 22
Spy with
expectations...




  Unit Test Fun: Mock Objects, Fixtures, Stubs & Dependency Injection I   Mayflower GmbH I 02. Dezember 2010 I 23
Model Mapper Beispiel

   class Application_Model_GuestbookMapper
   {
       protected $_dbTable;

       public function setDbTable(Zend_Db_Table_Abstract $dbTable)
       {
           $this->_dbTable = $dbTable;
           return $this;
       }

       public function getDbTable()
       {
           return $this->_dbTable;
       }

       public function getEmail() {}
       public function getComment() {}

       public function save(Application_Model_Guestbook $guestbook)
       {
           $data = array(
               'email'    => $guestbook->getEmail(),
               'comment' => $guestbook->getComment(),
           );

           $this->getDbTable()->insert($data);
       }
   }

                               Unit Test Fun: Mock Objects, Fixtures, Stubs & Dependency Injection I   Mayflower GmbH I 02. Dezember 2010 I 24
Testen der save() Funktion


class Applicatoin_Model_GuestbookMapperTest extends PHPUnit_Framework_TestCase
{
    public function testSave()
    {
        $modelStub = $this->getMock('Application_Model_Guestbook', array('getEmail', ,getComment'));

         $modelStub->expects($this->once())
                   ->method('getEmail')
                   ->will($this->returnValue('super@email.de'));

         $modelStub->expects($this->once())
                   ->method('getComment')
                   ->will($this->returnValue('super comment'));

         $tableMock = $this->getMock('Zend_Db_Table_Abstract', array('insert'), array(), '', false);
         $tableMock->expects($this->once())
                   ->method('insert')
                   ->with($this->equalTo(array(
                            'email' => 'super@email.de',
                            'comment' => 'super comment')));

         $model = new Application_Model_GuestbookMapper();
         $model->setDbTable($tableMock); // << MOCK
         $model->save($modelStub);       // << STUB
     }
}

                                    Unit Test Fun: Mock Objects, Fixtures, Stubs & Dependency Injection I   Mayflower GmbH I 02. Dezember 2010 I 25
Stub                                                                Mock
  Fake that                                                                Spy with
returns canned              !==                                  expectations...
    data...




              Unit Test Fun: Mock Objects, Fixtures, Stubs & Dependency Injection I   Mayflower GmbH I 02. Dezember 2010 I 26
Fixtures



Unit Test Fun: Mock Objects, Fixtures, Stubs & Dependency Injection I   Mayflower GmbH I 02. Dezember 2010 I 27
Set the world up
   in a known
     state ...



   Unit Test Fun: Mock Objects, Fixtures, Stubs & Dependency Injection I   Mayflower GmbH I 02. Dezember 2010 I 28
Fixture-Beispiel

       class Fixture extends PHPUnit_Framework_TestCase
       {
           protected $fixture;

           protected function setUp()
           {
               $this->fixture = array();
           }

           public function testEmpty()
           {
               $this->assertTrue(empty($this->fixture));
           }

           public function testPush()
           {
               array_push($this->fixture, 'foo');
               $this->assertEquals('foo', $this->fixture[0]);
           }

           public function testPop()
           {
               array_push($this->fixture, 'foo');
               $this->assertEquals('foo', array_pop($this->fixture));
               $this->assertTrue(empty($this->fixture));
           }
       }

                              Unit Test Fun: Mock Objects, Fixtures, Stubs & Dependency Injection I   Mayflower GmbH I 02. Dezember 2010 I 29
Method Stack


     Ablauf

               public static function setUpBeforeClass() { }



               protected function setUp() { }



               public function testMyTest() { /* TEST */ }



               protected function tearDown() { }



               protected function onNotSuccessfulTest(Exception $e) { }



               public static function tearDownAfterClass() { }




                          Unit Test Fun: Mock Objects, Fixtures, Stubs & Dependency Injection I   Mayflower GmbH I 02. Dezember 2010 I 30
Test Suite ...



 Unit Test Fun: Mock Objects, Fixtures, Stubs & Dependency Injection I   Mayflower GmbH I 02. Dezember 2010 I 31
...wirkt sich auf die
   Architektur aus.


     Unit Test Fun: Mock Objects, Fixtures, Stubs & Dependency Injection I   Mayflower GmbH I 02. Dezember 2010 I 32
Wenn nicht...



  Unit Test Fun: Mock Objects, Fixtures, Stubs & Dependency Injection I   Mayflower GmbH I 02. Dezember 2010 I 33
Developer


Titel der Präsentation I   Mayflower GmbH I xx. Juni 2010 I 34
Was kann man machen?



      Unit Test Fun: Mock Objects, Fixtures, Stubs & Dependency Injection I   Mayflower GmbH I 02. Dezember 2010 I 35
Production Code
  überarbeiten


   Unit Test Fun: Mock Objects, Fixtures, Stubs & Dependency Injection I   Mayflower GmbH I 02. Dezember 2010 I 36
Dependency Injection



      Unit Test Fun: Mock Objects, Fixtures, Stubs & Dependency Injection I   Mayflower GmbH I 02. Dezember 2010 I 37
Bemerkt?



Unit Test Fun: Mock Objects, Fixtures, Stubs & Dependency Injection I   Mayflower GmbH I 02. Dezember 2010 I 38
Dependency Injection

   class Application_Model_GuestbookMapper
   {
       protected $_dbTable;

       public function setDbTable(Zend_Db_Table_Abstract $dbTable)
       {
           $this->_dbTable = $dbTable;
           return $this;
       }

       public function getDbTable()
       {
           return $this->_dbTable;
       }

       public function getEmail() {}
       public function getComment() {}

       public function save(Application_Model_Guestbook $guestbook)
       {
           $data = array(
               'email'    => $guestbook->getEmail(),
               'comment' => $guestbook->getComment(),
           );

           $this->getDbTable()->insert($data);
       }
   }

                               Unit Test Fun: Mock Objects, Fixtures, Stubs & Dependency Injection I   Mayflower GmbH I 02. Dezember 2010 I 39
Besser aber ...



   Unit Test Fun: Mock Objects, Fixtures, Stubs & Dependency Injection I   Mayflower GmbH I 02. Dezember 2010 I 40
... Begeisterung sieht anders aus!




                                 Titel der Präsentation I   Mayflower GmbH I xx. Juni 2010 I 41
Was könnte noch helfen?



       Unit Test Fun: Mock Objects, Fixtures, Stubs & Dependency Injection I   Mayflower GmbH I 02. Dezember 2010 I 42
TDD?
Test Driven Development

                                                          [
                                                           ~~
                          [                                                         ~~
                           ~~                                                                ~~
                                                      ~~                                               ~~
                                                                   ~~                                            ~~
                                                                      ~
       Unit Test Fun: Mock Objects, Fixtures, Stubs & Dependency Injection I   Mayflower GmbH I 02. Dezember 2010 I 43
Probleme früh erkennen!



       Unit Test Fun: Mock Objects, Fixtures, Stubs & Dependency Injection I   Mayflower GmbH I 02. Dezember 2010 I 44
Uncle Bob´s
Three Rules of TDD




    Unit Test Fun: Mock Objects, Fixtures, Stubs & Dependency Injection I   Mayflower GmbH I 02. Dezember 2010 I 45
#1
 “   You are not allowed to write any

production code unless it is to make a
         failing unit test pass.




             Unit Test Fun: Mock Objects, Fixtures, Stubs & Dependency Injection I   Mayflower GmbH I 02. Dezember 2010 I 46
#2
“   You are not allowed to write any more of

a unit test than is sufficient to fail; and
      compilation failures are failures.




                Unit Test Fun: Mock Objects, Fixtures, Stubs & Dependency Injection I   Mayflower GmbH I 02. Dezember 2010 I 47
#3
“   You are not allowed to write any more

production code than is sufficient to pass
         the one failing unit test.




              Unit Test Fun: Mock Objects, Fixtures, Stubs & Dependency Injection I   Mayflower GmbH I 02. Dezember 2010 I 48
Und wieder...



  Unit Test Fun: Mock Objects, Fixtures, Stubs & Dependency Injection I   Mayflower GmbH I 02. Dezember 2010 I 49
Developer


Titel der Präsentation I   Mayflower GmbH I xx. Juni 2010 I 50
Und jetzt?



Unit Test Fun: Mock Objects, Fixtures, Stubs & Dependency Injection I   Mayflower GmbH I 02. Dezember 2010 I 51
Things get worst
 before they get
     better !



   Unit Test Fun: Mock Objects, Fixtures, Stubs & Dependency Injection I   Mayflower GmbH I 02. Dezember 2010 I 52
Monate später...




                   Titel der Präsentation I   Mayflower GmbH I xx. Juni 2010 I 53
Gibts noch was?



   Unit Test Fun: Mock Objects, Fixtures, Stubs & Dependency Injection I   Mayflower GmbH I 02. Dezember 2010 I 54
Darf ich vorstellen:
„Bug“




                Unit Test Fun: Mock Objects, Fixtures, Stubs & Dependency Injection I   Mayflower GmbH I 02. Dezember 2010 I 55
Regression Testing
        or
  Test your Bugs!



    Unit Test Fun: Mock Objects, Fixtures, Stubs & Dependency Injection I   Mayflower GmbH I 02. Dezember 2010 I 56
Regression Testing



  Bug
                class Calculate
                {
                    public function divide($dividend, $divisor)
    1               {
                        return $dividend / $divisor;
                    }
                }




    2           Warning: Division by zero in /srv/phpunit-slides/Calculate.php on line 7




                         Unit Test Fun: Mock Objects, Fixtures, Stubs & Dependency Injection I   Mayflower GmbH I 02. Dezember 2010 I 57
Regression Testing



  Test First!
                     /**
                       * Regression-Test BUG-123
                       *
                       * @group BUG-123
                       *
                       * @return void
    3                  */
                     public function testDivideByZero()
                     {
                          $calc = new Calculate();
                          $this->assertEquals(0, $calc->divide(1, 0));
                     }




                          Unit Test Fun: Mock Objects, Fixtures, Stubs & Dependency Injection I   Mayflower GmbH I 02. Dezember 2010 I 58
Regression Testing



  Bugfix

                class Calculate
                {
    4               public function divide($dividend, $divisor)
                    {
                        if (0 == $divisor) {
                            return 0;
                        }
                        return $dividend / $divisor;
                    }
                }




                         Unit Test Fun: Mock Objects, Fixtures, Stubs & Dependency Injection I   Mayflower GmbH I 02. Dezember 2010 I 59
Regression Testing



  phpunit

                slides$ phpunit --colors --verbose CalculateTest.php
                PHPUnit 3.5.5 by Sebastian Bergmann.
    5
                CalculateTest
                ......

                Time: 0 seconds, Memory: 5.25Mb

                OK (6 tests, 6 assertions)




                         Unit Test Fun: Mock Objects, Fixtures, Stubs & Dependency Injection I   Mayflower GmbH I 02. Dezember 2010 I 60
Regression Testing



  @group
                slides$ phpunit --colors --verbose --group BUG-123 CalculateTest.php
                PHPUnit 3.5.5 by Sebastian Bergmann.
    ?
                CalculateTest
                .

                Time: 0 seconds, Memory: 5.25Mb

                OK (1 tests, 1 assertions)




                     /**
                       * Regression-Test BUG-123
                       *
                       * @group BUG-123
                       *
                       * @return void
    ?                  */
                     public function testDivideByZero()
                     {

                          Unit Test Fun: Mock Objects, Fixtures, Stubs & Dependency Injection I   Mayflower GmbH I 02. Dezember 2010 I 61
Noch Fragen?



  Unit Test Fun: Mock Objects, Fixtures, Stubs & Dependency Injection I   Mayflower GmbH I 02. Dezember 2010 I 62
Quellen


I   Baby: ADDROX http://www.flickr.com/photos/addrox/2587484034/sizes/m/
I   Fish:   ADDROX http://www.flickr.com/photos/addrox/274632284/sizes/m/
I   Happy: ADDROX http://www.flickr.com/photos/addrox/2610064689/sizes/m/
I   Bug:    ADDROX http://www.flickr.com/photos/addrox/284649644/sizes/m/




                                 Unit Test Fun: Mock Objects, Fixtures, Stubs & Dependency Injection I   Mayflower GmbH I 02. Dezember 2010 I 63
Vielen Dank für Ihre Aufmerksamkeit!




Kontakt   Max Köhler
          max.koehler@mayflower.de
          +49 89 242054-1160

          Mayflower GmbH
          Mannhardtstr. 6
          80538 München



                                       © 2010 Mayflower GmbH

More Related Content

What's hot

Mock your way with Mockito
Mock your way with MockitoMock your way with Mockito
Mock your way with Mockito
Vitaly Polonetsky
 
Leveraging Symfony2 Forms
Leveraging Symfony2 FormsLeveraging Symfony2 Forms
Leveraging Symfony2 Forms
Bernhard Schussek
 
Zf2 how arrays will save your project
Zf2   how arrays will save your projectZf2   how arrays will save your project
Zf2 how arrays will save your project
Michelangelo van Dam
 
GeeCON 2012 Bad Tests, Good Tests
GeeCON 2012 Bad Tests, Good TestsGeeCON 2012 Bad Tests, Good Tests
GeeCON 2012 Bad Tests, Good Tests
Tomek Kaczanowski
 
Confitura 2012 Bad Tests, Good Tests
Confitura 2012 Bad Tests, Good TestsConfitura 2012 Bad Tests, Good Tests
Confitura 2012 Bad Tests, Good Tests
Tomek Kaczanowski
 
eROSE: Guiding programmers in Eclipse
eROSE: Guiding programmers in EclipseeROSE: Guiding programmers in Eclipse
eROSE: Guiding programmers in Eclipse
Thomas Zimmermann
 
Instant Dynamic Forms with #states
Instant Dynamic Forms with #statesInstant Dynamic Forms with #states
Instant Dynamic Forms with #states
Konstantin Käfer
 
A Spring Data’s Guide to Persistence
A Spring Data’s Guide to PersistenceA Spring Data’s Guide to Persistence
A Spring Data’s Guide to Persistence
VMware Tanzu
 
The django quiz
The django quizThe django quiz

What's hot (9)

Mock your way with Mockito
Mock your way with MockitoMock your way with Mockito
Mock your way with Mockito
 
Leveraging Symfony2 Forms
Leveraging Symfony2 FormsLeveraging Symfony2 Forms
Leveraging Symfony2 Forms
 
Zf2 how arrays will save your project
Zf2   how arrays will save your projectZf2   how arrays will save your project
Zf2 how arrays will save your project
 
GeeCON 2012 Bad Tests, Good Tests
GeeCON 2012 Bad Tests, Good TestsGeeCON 2012 Bad Tests, Good Tests
GeeCON 2012 Bad Tests, Good Tests
 
Confitura 2012 Bad Tests, Good Tests
Confitura 2012 Bad Tests, Good TestsConfitura 2012 Bad Tests, Good Tests
Confitura 2012 Bad Tests, Good Tests
 
eROSE: Guiding programmers in Eclipse
eROSE: Guiding programmers in EclipseeROSE: Guiding programmers in Eclipse
eROSE: Guiding programmers in Eclipse
 
Instant Dynamic Forms with #states
Instant Dynamic Forms with #statesInstant Dynamic Forms with #states
Instant Dynamic Forms with #states
 
A Spring Data’s Guide to Persistence
A Spring Data’s Guide to PersistenceA Spring Data’s Guide to Persistence
A Spring Data’s Guide to Persistence
 
The django quiz
The django quizThe django quiz
The django quiz
 

Similar to Unit Test Fun

Test doubles and EasyMock
Test doubles and EasyMockTest doubles and EasyMock
Test doubles and EasyMock
Rafael Antonio Gutiérrez Turullols
 
EasyMock for Java
EasyMock for JavaEasyMock for Java
EasyMock for Java
Deepak Singhvi
 
Ef Poco And Unit Testing
Ef Poco And Unit TestingEf Poco And Unit Testing
Ef Poco And Unit Testing
James Phillips
 
Mockito with a hint of PowerMock
Mockito with a hint of PowerMockMockito with a hint of PowerMock
Mockito with a hint of PowerMock
Ying Zhang
 
JUNit Presentation
JUNit PresentationJUNit Presentation
JUNit Presentation
Animesh Kumar
 
Adopting TDD - by Don McGreal
Adopting TDD - by Don McGrealAdopting TDD - by Don McGreal
Adopting TDD - by Don McGreal
Synerzip
 
Effective testing with pytest
Effective testing with pytestEffective testing with pytest
Effective testing with pytest
Hector Canto
 
UI Testing
UI TestingUI Testing
UI Testing
Josh Black
 
Secret unit testing tools no one ever told you about
Secret unit testing tools no one ever told you aboutSecret unit testing tools no one ever told you about
Secret unit testing tools no one ever told you about
Dror Helper
 
31b - JUnit and Mockito.pdf
31b - JUnit and Mockito.pdf31b - JUnit and Mockito.pdf
31b - JUnit and Mockito.pdf
gauravavam
 
Unit-testing and E2E testing in JS
Unit-testing and E2E testing in JSUnit-testing and E2E testing in JS
Unit-testing and E2E testing in JS
Michael Haberman
 
Javascript Ttesting
Javascript TtestingJavascript Ttesting
Javascript Ttesting
Mayflower GmbH
 
Need(le) for Speed - Effective Unit Testing for Java EE
Need(le) for Speed - Effective Unit Testing for Java EENeed(le) for Speed - Effective Unit Testing for Java EE
Need(le) for Speed - Effective Unit Testing for Java EE
hwilming
 
PHP Unit Testing in Yii
PHP Unit Testing in YiiPHP Unit Testing in Yii
PHP Unit Testing in Yii
IlPeach
 
Testable Javascript
Testable JavascriptTestable Javascript
Testable Javascript
Mark Trostler
 
Rhino Mocks
Rhino MocksRhino Mocks
Rhino Mocks
Anand Kumar Rajana
 
Google mock training
Google mock trainingGoogle mock training
Google mock training
Thierry Gayet
 
Unit testing basic
Unit testing basicUnit testing basic
Unit testing basic
Yuri Anischenko
 
Unit Testing and Why it Matters
Unit Testing and Why it MattersUnit Testing and Why it Matters
Unit Testing and Why it Matters
yahyaSadiiq
 
Asp netmvc e03
Asp netmvc e03Asp netmvc e03
Asp netmvc e03
Yu GUAN
 

Similar to Unit Test Fun (20)

Test doubles and EasyMock
Test doubles and EasyMockTest doubles and EasyMock
Test doubles and EasyMock
 
EasyMock for Java
EasyMock for JavaEasyMock for Java
EasyMock for Java
 
Ef Poco And Unit Testing
Ef Poco And Unit TestingEf Poco And Unit Testing
Ef Poco And Unit Testing
 
Mockito with a hint of PowerMock
Mockito with a hint of PowerMockMockito with a hint of PowerMock
Mockito with a hint of PowerMock
 
JUNit Presentation
JUNit PresentationJUNit Presentation
JUNit Presentation
 
Adopting TDD - by Don McGreal
Adopting TDD - by Don McGrealAdopting TDD - by Don McGreal
Adopting TDD - by Don McGreal
 
Effective testing with pytest
Effective testing with pytestEffective testing with pytest
Effective testing with pytest
 
UI Testing
UI TestingUI Testing
UI Testing
 
Secret unit testing tools no one ever told you about
Secret unit testing tools no one ever told you aboutSecret unit testing tools no one ever told you about
Secret unit testing tools no one ever told you about
 
31b - JUnit and Mockito.pdf
31b - JUnit and Mockito.pdf31b - JUnit and Mockito.pdf
31b - JUnit and Mockito.pdf
 
Unit-testing and E2E testing in JS
Unit-testing and E2E testing in JSUnit-testing and E2E testing in JS
Unit-testing and E2E testing in JS
 
Javascript Ttesting
Javascript TtestingJavascript Ttesting
Javascript Ttesting
 
Need(le) for Speed - Effective Unit Testing for Java EE
Need(le) for Speed - Effective Unit Testing for Java EENeed(le) for Speed - Effective Unit Testing for Java EE
Need(le) for Speed - Effective Unit Testing for Java EE
 
PHP Unit Testing in Yii
PHP Unit Testing in YiiPHP Unit Testing in Yii
PHP Unit Testing in Yii
 
Testable Javascript
Testable JavascriptTestable Javascript
Testable Javascript
 
Rhino Mocks
Rhino MocksRhino Mocks
Rhino Mocks
 
Google mock training
Google mock trainingGoogle mock training
Google mock training
 
Unit testing basic
Unit testing basicUnit testing basic
Unit testing basic
 
Unit Testing and Why it Matters
Unit Testing and Why it MattersUnit Testing and Why it Matters
Unit Testing and Why it Matters
 
Asp netmvc e03
Asp netmvc e03Asp netmvc e03
Asp netmvc e03
 

More from Mayflower GmbH

Mit Maintenance umgehen können- Fixt du noch Bugs oder lieferst du schon neue...
Mit Maintenance umgehen können- Fixt du noch Bugs oder lieferst du schon neue...Mit Maintenance umgehen können- Fixt du noch Bugs oder lieferst du schon neue...
Mit Maintenance umgehen können- Fixt du noch Bugs oder lieferst du schon neue...
Mayflower GmbH
 
Why and what is go
Why and what is goWhy and what is go
Why and what is go
Mayflower GmbH
 
Agile Anti-Patterns
Agile Anti-PatternsAgile Anti-Patterns
Agile Anti-Patterns
Mayflower GmbH
 
JavaScript Days 2015: Security
JavaScript Days 2015: SecurityJavaScript Days 2015: Security
JavaScript Days 2015: Security
Mayflower GmbH
 
Vom Entwickler zur Führungskraft
Vom Entwickler zur FührungskraftVom Entwickler zur Führungskraft
Vom Entwickler zur Führungskraft
Mayflower GmbH
 
Produktive teams
Produktive teamsProduktive teams
Produktive teams
Mayflower GmbH
 
Salt and pepper — native code in the browser Browser using Google native Client
Salt and pepper — native code in the browser Browser using Google native ClientSalt and pepper — native code in the browser Browser using Google native Client
Salt and pepper — native code in the browser Browser using Google native Client
Mayflower GmbH
 
Plugging holes — javascript memory leak debugging
Plugging holes — javascript memory leak debuggingPlugging holes — javascript memory leak debugging
Plugging holes — javascript memory leak debugging
Mayflower GmbH
 
Usability im web
Usability im webUsability im web
Usability im web
Mayflower GmbH
 
Rewrites überleben
Rewrites überlebenRewrites überleben
Rewrites überleben
Mayflower GmbH
 
JavaScript Security
JavaScript SecurityJavaScript Security
JavaScript Security
Mayflower GmbH
 
50 mal produktiver - oder warum ich gute Teams brauche und nicht gute Entwick...
50 mal produktiver - oder warum ich gute Teams brauche und nicht gute Entwick...50 mal produktiver - oder warum ich gute Teams brauche und nicht gute Entwick...
50 mal produktiver - oder warum ich gute Teams brauche und nicht gute Entwick...
Mayflower GmbH
 
Responsive Webdesign
Responsive WebdesignResponsive Webdesign
Responsive Webdesign
Mayflower GmbH
 
Native Cross-Platform-Apps mit Titanium Mobile und Alloy
Native Cross-Platform-Apps mit Titanium Mobile und AlloyNative Cross-Platform-Apps mit Titanium Mobile und Alloy
Native Cross-Platform-Apps mit Titanium Mobile und Alloy
Mayflower GmbH
 
Pair Programming Mythbusters
Pair Programming MythbustersPair Programming Mythbusters
Pair Programming Mythbusters
Mayflower GmbH
 
Shoeism - Frau im Glück
Shoeism - Frau im GlückShoeism - Frau im Glück
Shoeism - Frau im Glück
Mayflower GmbH
 
Bessere Software schneller liefern
Bessere Software schneller liefernBessere Software schneller liefern
Bessere Software schneller liefern
Mayflower GmbH
 
Von 0 auf 100 in 2 Sprints
Von 0 auf 100 in 2 SprintsVon 0 auf 100 in 2 Sprints
Von 0 auf 100 in 2 Sprints
Mayflower GmbH
 
Piwik anpassen und skalieren
Piwik anpassen und skalierenPiwik anpassen und skalieren
Piwik anpassen und skalieren
Mayflower GmbH
 
Agilitaet im E-Commerce - E-Commerce Breakfast
Agilitaet im E-Commerce - E-Commerce BreakfastAgilitaet im E-Commerce - E-Commerce Breakfast
Agilitaet im E-Commerce - E-Commerce Breakfast
Mayflower GmbH
 

More from Mayflower GmbH (20)

Mit Maintenance umgehen können- Fixt du noch Bugs oder lieferst du schon neue...
Mit Maintenance umgehen können- Fixt du noch Bugs oder lieferst du schon neue...Mit Maintenance umgehen können- Fixt du noch Bugs oder lieferst du schon neue...
Mit Maintenance umgehen können- Fixt du noch Bugs oder lieferst du schon neue...
 
Why and what is go
Why and what is goWhy and what is go
Why and what is go
 
Agile Anti-Patterns
Agile Anti-PatternsAgile Anti-Patterns
Agile Anti-Patterns
 
JavaScript Days 2015: Security
JavaScript Days 2015: SecurityJavaScript Days 2015: Security
JavaScript Days 2015: Security
 
Vom Entwickler zur Führungskraft
Vom Entwickler zur FührungskraftVom Entwickler zur Führungskraft
Vom Entwickler zur Führungskraft
 
Produktive teams
Produktive teamsProduktive teams
Produktive teams
 
Salt and pepper — native code in the browser Browser using Google native Client
Salt and pepper — native code in the browser Browser using Google native ClientSalt and pepper — native code in the browser Browser using Google native Client
Salt and pepper — native code in the browser Browser using Google native Client
 
Plugging holes — javascript memory leak debugging
Plugging holes — javascript memory leak debuggingPlugging holes — javascript memory leak debugging
Plugging holes — javascript memory leak debugging
 
Usability im web
Usability im webUsability im web
Usability im web
 
Rewrites überleben
Rewrites überlebenRewrites überleben
Rewrites überleben
 
JavaScript Security
JavaScript SecurityJavaScript Security
JavaScript Security
 
50 mal produktiver - oder warum ich gute Teams brauche und nicht gute Entwick...
50 mal produktiver - oder warum ich gute Teams brauche und nicht gute Entwick...50 mal produktiver - oder warum ich gute Teams brauche und nicht gute Entwick...
50 mal produktiver - oder warum ich gute Teams brauche und nicht gute Entwick...
 
Responsive Webdesign
Responsive WebdesignResponsive Webdesign
Responsive Webdesign
 
Native Cross-Platform-Apps mit Titanium Mobile und Alloy
Native Cross-Platform-Apps mit Titanium Mobile und AlloyNative Cross-Platform-Apps mit Titanium Mobile und Alloy
Native Cross-Platform-Apps mit Titanium Mobile und Alloy
 
Pair Programming Mythbusters
Pair Programming MythbustersPair Programming Mythbusters
Pair Programming Mythbusters
 
Shoeism - Frau im Glück
Shoeism - Frau im GlückShoeism - Frau im Glück
Shoeism - Frau im Glück
 
Bessere Software schneller liefern
Bessere Software schneller liefernBessere Software schneller liefern
Bessere Software schneller liefern
 
Von 0 auf 100 in 2 Sprints
Von 0 auf 100 in 2 SprintsVon 0 auf 100 in 2 Sprints
Von 0 auf 100 in 2 Sprints
 
Piwik anpassen und skalieren
Piwik anpassen und skalierenPiwik anpassen und skalieren
Piwik anpassen und skalieren
 
Agilitaet im E-Commerce - E-Commerce Breakfast
Agilitaet im E-Commerce - E-Commerce BreakfastAgilitaet im E-Commerce - E-Commerce Breakfast
Agilitaet im E-Commerce - E-Commerce Breakfast
 

Recently uploaded

Connector Corner: Seamlessly power UiPath Apps, GenAI with prebuilt connectors
Connector Corner: Seamlessly power UiPath Apps, GenAI with prebuilt connectorsConnector Corner: Seamlessly power UiPath Apps, GenAI with prebuilt connectors
Connector Corner: Seamlessly power UiPath Apps, GenAI with prebuilt connectors
DianaGray10
 
Apps Break Data
Apps Break DataApps Break Data
Apps Break Data
Ivo Velitchkov
 
"$10 thousand per minute of downtime: architecture, queues, streaming and fin...
"$10 thousand per minute of downtime: architecture, queues, streaming and fin..."$10 thousand per minute of downtime: architecture, queues, streaming and fin...
"$10 thousand per minute of downtime: architecture, queues, streaming and fin...
Fwdays
 
Biomedical Knowledge Graphs for Data Scientists and Bioinformaticians
Biomedical Knowledge Graphs for Data Scientists and BioinformaticiansBiomedical Knowledge Graphs for Data Scientists and Bioinformaticians
Biomedical Knowledge Graphs for Data Scientists and Bioinformaticians
Neo4j
 
Choosing The Best AWS Service For Your Website + API.pptx
Choosing The Best AWS Service For Your Website + API.pptxChoosing The Best AWS Service For Your Website + API.pptx
Choosing The Best AWS Service For Your Website + API.pptx
Brandon Minnick, MBA
 
Y-Combinator seed pitch deck template PP
Y-Combinator seed pitch deck template PPY-Combinator seed pitch deck template PP
Y-Combinator seed pitch deck template PP
c5vrf27qcz
 
Skybuffer SAM4U tool for SAP license adoption
Skybuffer SAM4U tool for SAP license adoptionSkybuffer SAM4U tool for SAP license adoption
Skybuffer SAM4U tool for SAP license adoption
Tatiana Kojar
 
Demystifying Knowledge Management through Storytelling
Demystifying Knowledge Management through StorytellingDemystifying Knowledge Management through Storytelling
Demystifying Knowledge Management through Storytelling
Enterprise Knowledge
 
Must Know Postgres Extension for DBA and Developer during Migration
Must Know Postgres Extension for DBA and Developer during MigrationMust Know Postgres Extension for DBA and Developer during Migration
Must Know Postgres Extension for DBA and Developer during Migration
Mydbops
 
Your One-Stop Shop for Python Success: Top 10 US Python Development Providers
Your One-Stop Shop for Python Success: Top 10 US Python Development ProvidersYour One-Stop Shop for Python Success: Top 10 US Python Development Providers
Your One-Stop Shop for Python Success: Top 10 US Python Development Providers
akankshawande
 
GNSS spoofing via SDR (Criptored Talks 2024)
GNSS spoofing via SDR (Criptored Talks 2024)GNSS spoofing via SDR (Criptored Talks 2024)
GNSS spoofing via SDR (Criptored Talks 2024)
Javier Junquera
 
Taking AI to the Next Level in Manufacturing.pdf
Taking AI to the Next Level in Manufacturing.pdfTaking AI to the Next Level in Manufacturing.pdf
Taking AI to the Next Level in Manufacturing.pdf
ssuserfac0301
 
PRODUCT LISTING OPTIMIZATION PRESENTATION.pptx
PRODUCT LISTING OPTIMIZATION PRESENTATION.pptxPRODUCT LISTING OPTIMIZATION PRESENTATION.pptx
PRODUCT LISTING OPTIMIZATION PRESENTATION.pptx
christinelarrosa
 
Fueling AI with Great Data with Airbyte Webinar
Fueling AI with Great Data with Airbyte WebinarFueling AI with Great Data with Airbyte Webinar
Fueling AI with Great Data with Airbyte Webinar
Zilliz
 
"Choosing proper type of scaling", Olena Syrota
"Choosing proper type of scaling", Olena Syrota"Choosing proper type of scaling", Olena Syrota
"Choosing proper type of scaling", Olena Syrota
Fwdays
 
zkStudyClub - LatticeFold: A Lattice-based Folding Scheme and its Application...
zkStudyClub - LatticeFold: A Lattice-based Folding Scheme and its Application...zkStudyClub - LatticeFold: A Lattice-based Folding Scheme and its Application...
zkStudyClub - LatticeFold: A Lattice-based Folding Scheme and its Application...
Alex Pruden
 
[OReilly Superstream] Occupy the Space: A grassroots guide to engineering (an...
[OReilly Superstream] Occupy the Space: A grassroots guide to engineering (an...[OReilly Superstream] Occupy the Space: A grassroots guide to engineering (an...
[OReilly Superstream] Occupy the Space: A grassroots guide to engineering (an...
Jason Yip
 
The Microsoft 365 Migration Tutorial For Beginner.pptx
The Microsoft 365 Migration Tutorial For Beginner.pptxThe Microsoft 365 Migration Tutorial For Beginner.pptx
The Microsoft 365 Migration Tutorial For Beginner.pptx
operationspcvita
 
Astute Business Solutions | Oracle Cloud Partner |
Astute Business Solutions | Oracle Cloud Partner |Astute Business Solutions | Oracle Cloud Partner |
Astute Business Solutions | Oracle Cloud Partner |
AstuteBusiness
 
Christine's Supplier Sourcing Presentaion.pptx
Christine's Supplier Sourcing Presentaion.pptxChristine's Supplier Sourcing Presentaion.pptx
Christine's Supplier Sourcing Presentaion.pptx
christinelarrosa
 

Recently uploaded (20)

Connector Corner: Seamlessly power UiPath Apps, GenAI with prebuilt connectors
Connector Corner: Seamlessly power UiPath Apps, GenAI with prebuilt connectorsConnector Corner: Seamlessly power UiPath Apps, GenAI with prebuilt connectors
Connector Corner: Seamlessly power UiPath Apps, GenAI with prebuilt connectors
 
Apps Break Data
Apps Break DataApps Break Data
Apps Break Data
 
"$10 thousand per minute of downtime: architecture, queues, streaming and fin...
"$10 thousand per minute of downtime: architecture, queues, streaming and fin..."$10 thousand per minute of downtime: architecture, queues, streaming and fin...
"$10 thousand per minute of downtime: architecture, queues, streaming and fin...
 
Biomedical Knowledge Graphs for Data Scientists and Bioinformaticians
Biomedical Knowledge Graphs for Data Scientists and BioinformaticiansBiomedical Knowledge Graphs for Data Scientists and Bioinformaticians
Biomedical Knowledge Graphs for Data Scientists and Bioinformaticians
 
Choosing The Best AWS Service For Your Website + API.pptx
Choosing The Best AWS Service For Your Website + API.pptxChoosing The Best AWS Service For Your Website + API.pptx
Choosing The Best AWS Service For Your Website + API.pptx
 
Y-Combinator seed pitch deck template PP
Y-Combinator seed pitch deck template PPY-Combinator seed pitch deck template PP
Y-Combinator seed pitch deck template PP
 
Skybuffer SAM4U tool for SAP license adoption
Skybuffer SAM4U tool for SAP license adoptionSkybuffer SAM4U tool for SAP license adoption
Skybuffer SAM4U tool for SAP license adoption
 
Demystifying Knowledge Management through Storytelling
Demystifying Knowledge Management through StorytellingDemystifying Knowledge Management through Storytelling
Demystifying Knowledge Management through Storytelling
 
Must Know Postgres Extension for DBA and Developer during Migration
Must Know Postgres Extension for DBA and Developer during MigrationMust Know Postgres Extension for DBA and Developer during Migration
Must Know Postgres Extension for DBA and Developer during Migration
 
Your One-Stop Shop for Python Success: Top 10 US Python Development Providers
Your One-Stop Shop for Python Success: Top 10 US Python Development ProvidersYour One-Stop Shop for Python Success: Top 10 US Python Development Providers
Your One-Stop Shop for Python Success: Top 10 US Python Development Providers
 
GNSS spoofing via SDR (Criptored Talks 2024)
GNSS spoofing via SDR (Criptored Talks 2024)GNSS spoofing via SDR (Criptored Talks 2024)
GNSS spoofing via SDR (Criptored Talks 2024)
 
Taking AI to the Next Level in Manufacturing.pdf
Taking AI to the Next Level in Manufacturing.pdfTaking AI to the Next Level in Manufacturing.pdf
Taking AI to the Next Level in Manufacturing.pdf
 
PRODUCT LISTING OPTIMIZATION PRESENTATION.pptx
PRODUCT LISTING OPTIMIZATION PRESENTATION.pptxPRODUCT LISTING OPTIMIZATION PRESENTATION.pptx
PRODUCT LISTING OPTIMIZATION PRESENTATION.pptx
 
Fueling AI with Great Data with Airbyte Webinar
Fueling AI with Great Data with Airbyte WebinarFueling AI with Great Data with Airbyte Webinar
Fueling AI with Great Data with Airbyte Webinar
 
"Choosing proper type of scaling", Olena Syrota
"Choosing proper type of scaling", Olena Syrota"Choosing proper type of scaling", Olena Syrota
"Choosing proper type of scaling", Olena Syrota
 
zkStudyClub - LatticeFold: A Lattice-based Folding Scheme and its Application...
zkStudyClub - LatticeFold: A Lattice-based Folding Scheme and its Application...zkStudyClub - LatticeFold: A Lattice-based Folding Scheme and its Application...
zkStudyClub - LatticeFold: A Lattice-based Folding Scheme and its Application...
 
[OReilly Superstream] Occupy the Space: A grassroots guide to engineering (an...
[OReilly Superstream] Occupy the Space: A grassroots guide to engineering (an...[OReilly Superstream] Occupy the Space: A grassroots guide to engineering (an...
[OReilly Superstream] Occupy the Space: A grassroots guide to engineering (an...
 
The Microsoft 365 Migration Tutorial For Beginner.pptx
The Microsoft 365 Migration Tutorial For Beginner.pptxThe Microsoft 365 Migration Tutorial For Beginner.pptx
The Microsoft 365 Migration Tutorial For Beginner.pptx
 
Astute Business Solutions | Oracle Cloud Partner |
Astute Business Solutions | Oracle Cloud Partner |Astute Business Solutions | Oracle Cloud Partner |
Astute Business Solutions | Oracle Cloud Partner |
 
Christine's Supplier Sourcing Presentaion.pptx
Christine's Supplier Sourcing Presentaion.pptxChristine's Supplier Sourcing Presentaion.pptx
Christine's Supplier Sourcing Presentaion.pptx
 

Unit Test Fun

  • 1. Unit Test Fun: Mock Objects, Fixtures, Stubs & Dependency Injection Max Köhler I 02. Dezember 2010 © 2010 Mayflower GmbH
  • 2. Wer macht UnitTests? Unit Test Fun: Mock Objects, Fixtures, Stubs & Dependency Injection I Mayflower GmbH I 02. Dezember 2010 I 2
  • 3. Code Coverage? Unit Test Fun: Mock Objects, Fixtures, Stubs & Dependency Injection I Mayflower GmbH I 02. Dezember 2010 I 3
  • 4. Wer glaubt, dass die Tests gut sind? Unit Test Fun: Mock Objects, Fixtures, Stubs & Dependency Injection I Mayflower GmbH I 02. Dezember 2010 I 4
  • 5. Kann die Qualität gesteigert werden? 100% 0% Unit Test Fun: Mock Objects, Fixtures, Stubs & Dependency Injection I Mayflower GmbH I 02. Dezember 2010 I 5
  • 6. Test der kompletten Architektur? Unit Test Fun: Mock Objects, Fixtures, Stubs & Dependency Injection I Mayflower GmbH I 02. Dezember 2010 I 6
  • 7. MVC? Controller View Model Unit Test Fun: Mock Objects, Fixtures, Stubs & Dependency Injection I Mayflower GmbH I 02. Dezember 2010 I 7
  • 8. Wie testet Ihr eure Models? Unit Test Fun: Mock Objects, Fixtures, Stubs & Dependency Injection I Mayflower GmbH I 02. Dezember 2010 I 8
  • 9. Direkter DB-Zugriff? Unit Test Fun: Mock Objects, Fixtures, Stubs & Dependency Injection I Mayflower GmbH I 02. Dezember 2010 I 9
  • 10. Keine UnitTests! STOP Unit Test Fun: Mock Objects, Fixtures, Stubs & Dependency Injection I Mayflower GmbH I 02. Dezember 2010 I 10
  • 11. Integration Tests! Unit Test Fun: Mock Objects, Fixtures, Stubs & Dependency Injection I Mayflower GmbH I 02. Dezember 2010 I 11
  • 12. Wie testet Ihr eure Controller? Unit Test Fun: Mock Objects, Fixtures, Stubs & Dependency Injection I Mayflower GmbH I 02. Dezember 2010 I 12
  • 13. Routes, Auth-Mock, Session-Mock, ...? Unit Test Fun: Mock Objects, Fixtures, Stubs & Dependency Injection I Mayflower GmbH I 02. Dezember 2010 I 13
  • 14. Keine UnitTests! STOP Unit Test Fun: Mock Objects, Fixtures, Stubs & Dependency Injection I Mayflower GmbH I 02. Dezember 2010 I 14
  • 15. Was wollen wir testen? Unit Test Fun: Mock Objects, Fixtures, Stubs & Dependency Injection I Mayflower GmbH I 02. Dezember 2010 I 15
  • 16. Integration Regression Testing Testing Unit Testing System - Integration Testing Acceptance Testing System Testing Unit Test Fun: Mock Objects, Fixtures, Stubs & Dependency Injection I Mayflower GmbH I 02. Dezember 2010 I 16
  • 17. The goal of unit testing is to isolate each part of the program and show that the individual parts are correct Unit Test Fun: Mock Objects, Fixtures, Stubs & Dependency Injection I Mayflower GmbH I 02. Dezember 2010 I 17
  • 18. Test Doubles Unit Test Fun: Mock Objects, Fixtures, Stubs & Dependency Injection I Mayflower GmbH I 02. Dezember 2010 I 18
  • 19. Stubs Unit Test Fun: Mock Objects, Fixtures, Stubs & Dependency Injection I Mayflower GmbH I 02. Dezember 2010 I 19
  • 20. Fake that returns canned data... Unit Test Fun: Mock Objects, Fixtures, Stubs & Dependency Injection I Mayflower GmbH I 02. Dezember 2010 I 20
  • 21. Beispiel für ein Auth-Stub $storageData = array( 'accountId' => 29, 'username' => 'Hugo', 'jid' => 'hugo@example.org'); $storage = $this->getMock('Zend_Auth_Storage_Session', array('read')); $storage->expects($this->any()) ->method('read') ->will($this->returnValue($storageData)); Zend_Auth::getInstance()->setStorage($storage); // ... /* * Bei jedem Aufruf wird nun das Mock als Storage * verwendet und dessen Daten ausgelesen */ $session = Zend_Auth::getInstance()->getIdentity(); Unit Test Fun: Mock Objects, Fixtures, Stubs & Dependency Injection I Mayflower GmbH I 02. Dezember 2010 I 21
  • 22. Mocks Unit Test Fun: Mock Objects, Fixtures, Stubs & Dependency Injection I Mayflower GmbH I 02. Dezember 2010 I 22
  • 23. Spy with expectations... Unit Test Fun: Mock Objects, Fixtures, Stubs & Dependency Injection I Mayflower GmbH I 02. Dezember 2010 I 23
  • 24. Model Mapper Beispiel class Application_Model_GuestbookMapper { protected $_dbTable; public function setDbTable(Zend_Db_Table_Abstract $dbTable) { $this->_dbTable = $dbTable; return $this; } public function getDbTable() { return $this->_dbTable; } public function getEmail() {} public function getComment() {} public function save(Application_Model_Guestbook $guestbook) { $data = array( 'email' => $guestbook->getEmail(), 'comment' => $guestbook->getComment(), ); $this->getDbTable()->insert($data); } } Unit Test Fun: Mock Objects, Fixtures, Stubs & Dependency Injection I Mayflower GmbH I 02. Dezember 2010 I 24
  • 25. Testen der save() Funktion class Applicatoin_Model_GuestbookMapperTest extends PHPUnit_Framework_TestCase { public function testSave() { $modelStub = $this->getMock('Application_Model_Guestbook', array('getEmail', ,getComment')); $modelStub->expects($this->once()) ->method('getEmail') ->will($this->returnValue('super@email.de')); $modelStub->expects($this->once()) ->method('getComment') ->will($this->returnValue('super comment')); $tableMock = $this->getMock('Zend_Db_Table_Abstract', array('insert'), array(), '', false); $tableMock->expects($this->once()) ->method('insert') ->with($this->equalTo(array( 'email' => 'super@email.de', 'comment' => 'super comment'))); $model = new Application_Model_GuestbookMapper(); $model->setDbTable($tableMock); // << MOCK $model->save($modelStub); // << STUB } } Unit Test Fun: Mock Objects, Fixtures, Stubs & Dependency Injection I Mayflower GmbH I 02. Dezember 2010 I 25
  • 26. Stub Mock Fake that Spy with returns canned !== expectations... data... Unit Test Fun: Mock Objects, Fixtures, Stubs & Dependency Injection I Mayflower GmbH I 02. Dezember 2010 I 26
  • 27. Fixtures Unit Test Fun: Mock Objects, Fixtures, Stubs & Dependency Injection I Mayflower GmbH I 02. Dezember 2010 I 27
  • 28. Set the world up in a known state ... Unit Test Fun: Mock Objects, Fixtures, Stubs & Dependency Injection I Mayflower GmbH I 02. Dezember 2010 I 28
  • 29. Fixture-Beispiel class Fixture extends PHPUnit_Framework_TestCase { protected $fixture; protected function setUp() { $this->fixture = array(); } public function testEmpty() { $this->assertTrue(empty($this->fixture)); } public function testPush() { array_push($this->fixture, 'foo'); $this->assertEquals('foo', $this->fixture[0]); } public function testPop() { array_push($this->fixture, 'foo'); $this->assertEquals('foo', array_pop($this->fixture)); $this->assertTrue(empty($this->fixture)); } } Unit Test Fun: Mock Objects, Fixtures, Stubs & Dependency Injection I Mayflower GmbH I 02. Dezember 2010 I 29
  • 30. Method Stack Ablauf public static function setUpBeforeClass() { } protected function setUp() { } public function testMyTest() { /* TEST */ } protected function tearDown() { } protected function onNotSuccessfulTest(Exception $e) { } public static function tearDownAfterClass() { } Unit Test Fun: Mock Objects, Fixtures, Stubs & Dependency Injection I Mayflower GmbH I 02. Dezember 2010 I 30
  • 31. Test Suite ... Unit Test Fun: Mock Objects, Fixtures, Stubs & Dependency Injection I Mayflower GmbH I 02. Dezember 2010 I 31
  • 32. ...wirkt sich auf die Architektur aus. Unit Test Fun: Mock Objects, Fixtures, Stubs & Dependency Injection I Mayflower GmbH I 02. Dezember 2010 I 32
  • 33. Wenn nicht... Unit Test Fun: Mock Objects, Fixtures, Stubs & Dependency Injection I Mayflower GmbH I 02. Dezember 2010 I 33
  • 34. Developer Titel der Präsentation I Mayflower GmbH I xx. Juni 2010 I 34
  • 35. Was kann man machen? Unit Test Fun: Mock Objects, Fixtures, Stubs & Dependency Injection I Mayflower GmbH I 02. Dezember 2010 I 35
  • 36. Production Code überarbeiten Unit Test Fun: Mock Objects, Fixtures, Stubs & Dependency Injection I Mayflower GmbH I 02. Dezember 2010 I 36
  • 37. Dependency Injection Unit Test Fun: Mock Objects, Fixtures, Stubs & Dependency Injection I Mayflower GmbH I 02. Dezember 2010 I 37
  • 38. Bemerkt? Unit Test Fun: Mock Objects, Fixtures, Stubs & Dependency Injection I Mayflower GmbH I 02. Dezember 2010 I 38
  • 39. Dependency Injection class Application_Model_GuestbookMapper { protected $_dbTable; public function setDbTable(Zend_Db_Table_Abstract $dbTable) { $this->_dbTable = $dbTable; return $this; } public function getDbTable() { return $this->_dbTable; } public function getEmail() {} public function getComment() {} public function save(Application_Model_Guestbook $guestbook) { $data = array( 'email' => $guestbook->getEmail(), 'comment' => $guestbook->getComment(), ); $this->getDbTable()->insert($data); } } Unit Test Fun: Mock Objects, Fixtures, Stubs & Dependency Injection I Mayflower GmbH I 02. Dezember 2010 I 39
  • 40. Besser aber ... Unit Test Fun: Mock Objects, Fixtures, Stubs & Dependency Injection I Mayflower GmbH I 02. Dezember 2010 I 40
  • 41. ... Begeisterung sieht anders aus! Titel der Präsentation I Mayflower GmbH I xx. Juni 2010 I 41
  • 42. Was könnte noch helfen? Unit Test Fun: Mock Objects, Fixtures, Stubs & Dependency Injection I Mayflower GmbH I 02. Dezember 2010 I 42
  • 43. TDD? Test Driven Development [ ~~ [ ~~ ~~ ~~ ~~ ~~ ~~ ~~ ~ Unit Test Fun: Mock Objects, Fixtures, Stubs & Dependency Injection I Mayflower GmbH I 02. Dezember 2010 I 43
  • 44. Probleme früh erkennen! Unit Test Fun: Mock Objects, Fixtures, Stubs & Dependency Injection I Mayflower GmbH I 02. Dezember 2010 I 44
  • 45. Uncle Bob´s Three Rules of TDD Unit Test Fun: Mock Objects, Fixtures, Stubs & Dependency Injection I Mayflower GmbH I 02. Dezember 2010 I 45
  • 46. #1 “ You are not allowed to write any production code unless it is to make a failing unit test pass. Unit Test Fun: Mock Objects, Fixtures, Stubs & Dependency Injection I Mayflower GmbH I 02. Dezember 2010 I 46
  • 47. #2 “ You are not allowed to write any more of a unit test than is sufficient to fail; and compilation failures are failures. Unit Test Fun: Mock Objects, Fixtures, Stubs & Dependency Injection I Mayflower GmbH I 02. Dezember 2010 I 47
  • 48. #3 “ You are not allowed to write any more production code than is sufficient to pass the one failing unit test. Unit Test Fun: Mock Objects, Fixtures, Stubs & Dependency Injection I Mayflower GmbH I 02. Dezember 2010 I 48
  • 49. Und wieder... Unit Test Fun: Mock Objects, Fixtures, Stubs & Dependency Injection I Mayflower GmbH I 02. Dezember 2010 I 49
  • 50. Developer Titel der Präsentation I Mayflower GmbH I xx. Juni 2010 I 50
  • 51. Und jetzt? Unit Test Fun: Mock Objects, Fixtures, Stubs & Dependency Injection I Mayflower GmbH I 02. Dezember 2010 I 51
  • 52. Things get worst before they get better ! Unit Test Fun: Mock Objects, Fixtures, Stubs & Dependency Injection I Mayflower GmbH I 02. Dezember 2010 I 52
  • 53. Monate später... Titel der Präsentation I Mayflower GmbH I xx. Juni 2010 I 53
  • 54. Gibts noch was? Unit Test Fun: Mock Objects, Fixtures, Stubs & Dependency Injection I Mayflower GmbH I 02. Dezember 2010 I 54
  • 55. Darf ich vorstellen: „Bug“ Unit Test Fun: Mock Objects, Fixtures, Stubs & Dependency Injection I Mayflower GmbH I 02. Dezember 2010 I 55
  • 56. Regression Testing or Test your Bugs! Unit Test Fun: Mock Objects, Fixtures, Stubs & Dependency Injection I Mayflower GmbH I 02. Dezember 2010 I 56
  • 57. Regression Testing Bug class Calculate { public function divide($dividend, $divisor) 1 { return $dividend / $divisor; } } 2 Warning: Division by zero in /srv/phpunit-slides/Calculate.php on line 7 Unit Test Fun: Mock Objects, Fixtures, Stubs & Dependency Injection I Mayflower GmbH I 02. Dezember 2010 I 57
  • 58. Regression Testing Test First! /** * Regression-Test BUG-123 * * @group BUG-123 * * @return void 3 */ public function testDivideByZero() { $calc = new Calculate(); $this->assertEquals(0, $calc->divide(1, 0)); } Unit Test Fun: Mock Objects, Fixtures, Stubs & Dependency Injection I Mayflower GmbH I 02. Dezember 2010 I 58
  • 59. Regression Testing Bugfix class Calculate { 4 public function divide($dividend, $divisor) { if (0 == $divisor) { return 0; } return $dividend / $divisor; } } Unit Test Fun: Mock Objects, Fixtures, Stubs & Dependency Injection I Mayflower GmbH I 02. Dezember 2010 I 59
  • 60. Regression Testing phpunit slides$ phpunit --colors --verbose CalculateTest.php PHPUnit 3.5.5 by Sebastian Bergmann. 5 CalculateTest ...... Time: 0 seconds, Memory: 5.25Mb OK (6 tests, 6 assertions) Unit Test Fun: Mock Objects, Fixtures, Stubs & Dependency Injection I Mayflower GmbH I 02. Dezember 2010 I 60
  • 61. Regression Testing @group slides$ phpunit --colors --verbose --group BUG-123 CalculateTest.php PHPUnit 3.5.5 by Sebastian Bergmann. ? CalculateTest . Time: 0 seconds, Memory: 5.25Mb OK (1 tests, 1 assertions) /** * Regression-Test BUG-123 * * @group BUG-123 * * @return void ? */ public function testDivideByZero() { Unit Test Fun: Mock Objects, Fixtures, Stubs & Dependency Injection I Mayflower GmbH I 02. Dezember 2010 I 61
  • 62. Noch Fragen? Unit Test Fun: Mock Objects, Fixtures, Stubs & Dependency Injection I Mayflower GmbH I 02. Dezember 2010 I 62
  • 63. Quellen I Baby: ADDROX http://www.flickr.com/photos/addrox/2587484034/sizes/m/ I Fish: ADDROX http://www.flickr.com/photos/addrox/274632284/sizes/m/ I Happy: ADDROX http://www.flickr.com/photos/addrox/2610064689/sizes/m/ I Bug: ADDROX http://www.flickr.com/photos/addrox/284649644/sizes/m/ Unit Test Fun: Mock Objects, Fixtures, Stubs & Dependency Injection I Mayflower GmbH I 02. Dezember 2010 I 63
  • 64. Vielen Dank für Ihre Aufmerksamkeit! Kontakt Max Köhler max.koehler@mayflower.de +49 89 242054-1160 Mayflower GmbH Mannhardtstr. 6 80538 München © 2010 Mayflower GmbH