SlideShare une entreprise Scribd logo
1  sur  48
Télécharger pour lire hors ligne
Unit-Testing Bad-Practices
            by Example

                              Benjamin Eberlei
                                 direkt effekt GmbH

                              IPC 09, Karlsruhe


Eberlei (direkt effekt GmbH)    Unit-Testing Bad-Practices   IPC 09, Karlsruhe   1 / 47
About Me

          Benjamin Eberlei
          direkt effekt GmBH
          (digital marketing)
          Open Source contributor
          (Zend Framework and Doctrine 2)
          Twitter @beberlei
          Blog: www.whitewashing.de
Eberlei (direkt effekt GmbH)   Unit-Testing Bad-Practices   IPC 09, Karlsruhe   2 / 47
And You?




Eberlei (direkt effekt GmbH)   Unit-Testing Bad-Practices   IPC 09, Karlsruhe   3 / 47
Why Test Quality Matters




Eberlei (direkt effekt GmbH)   Unit-Testing Bad-Practices   IPC 09, Karlsruhe   4 / 47
“We spent 90% of the time
      modifying existing tests to
      acommodate for a relatively
      minor change.“
      (G. Meszaros, xUnit Test Patterns)




Eberlei (direkt effekt GmbH)   Unit-Testing Bad-Practices   IPC 09, Karlsruhe   5 / 47
Safety Net vs Dead Weight




Eberlei (direkt effekt GmbH)   Unit-Testing Bad-Practices   IPC 09, Karlsruhe   6 / 47
Test Smells

                                       “Smell you later!”
                                       (Nelson, The Simpsons)




Eberlei (direkt effekt GmbH)   Unit-Testing Bad-Practices   IPC 09, Karlsruhe   7 / 47
Code Duplication




Eberlei (direkt effekt GmbH)   Unit-Testing Bad-Practices   IPC 09, Karlsruhe   8 / 47
ZF Controller Action
   public function testInitView ()
   {
       Zen d_ C o n t r o l l e r _ Front :: getInstance () ->
            s e t C o n t r o l l er Dir ec to ry ( ’/ _files ’) ;
       require_once ’/ _files / ViewController . php ’;
       $controller = new ViewController (
             new Z e n d _ C o n t r o l l e r _ R e q u e s t _ H t t p () ,
             new Z e n d _ C o n t r o l l e r _ R e s p o n s e _ C l i ()
       );
       $view = $controller - > initView () ;
       $this - > assertTrue ( $view instanceof Zend_View ) ;
       $scriptPath = $view - > getScriptPaths () ;
       $this - > assertTrue ( is_array ( $scriptPath ) ) ;
       $this - > assertEquals ( ’/ views / scripts / ’ , $scriptPath [0])
           ;
   }




Eberlei (direkt effekt GmbH)   Unit-Testing Bad-Practices   IPC 09, Karlsruhe   9 / 47
ZF Controller Action 2

   public function testRenderByName ()
   {
       $request = new Z e n d _ C o n t r o l l e r _ R e q u e s t _ H t t p () ;
       $request - > set ControllerName ( ’ view ’)
                     -> setActionName ( ’ test ’) ;
       $response = new Z e n d _ C o n t r o l l e r _ R e s p o n s e _ C l i () ;
       Zen d_ C o n t r o l l e r _ Front :: getInstance () ->
            s e t C o n t r o l l er Dir ec to ry ( ’/ _files ’) ;
       require_once ’/ _files / ViewController . php ’;
       $controller = new ViewController ( $request , $response ) ;

        $controller - > testAction () ;
        $this - > assertContains ( ’ In the index action view ’ ,
            $response - > getBody () ) ;
   }




Eberlei (direkt effekt GmbH)   Unit-Testing Bad-Practices   IPC 09, Karlsruhe   10 / 47
ZF Controller Refactoring
  Extract Test Utility Method:
   public function c r e ateViewController ( $controllerName = null ,
        $actionName = null )
   {
       $request = new Z e n d _ C o n t r o l l e r _ R e q u e s t _ H t t p () ;
       if ( $controllerName !== null ) {
             $request - > setControllerName ( $controllerName ) ;
       }
       if ( $actionName !== null ) {
             $request - > setActionName ( $actionName ) ;
       }
       $response = new Z e n d _ C o n t r o l l e r _ R e s p o n s e _ C l i () ;
        Zen d_ C o n t r o l l e r _ Front :: getInstance ()
             -> s e t C o n t r o l le rD ire ct or y ( ’/ _files ’) ;
        require_once ’/ _files / ViewController . php ’;

        return new ViewController ( $request , $response ) ;
   }


Eberlei (direkt effekt GmbH)    Unit-Testing Bad-Practices   IPC 09, Karlsruhe   11 / 47
ZF Controller Refactoring 2
   public function t e s tI nit Vi ew Ref ac to red ()
   {
       // fixture setup
       $controller = $this - > createViewController () ;

        // execution
        $view = $controller - > initView () ;
        $scriptPath = $view - > getScriptPaths () ;

        // assertions
        $this - > assertTrue ( $view instanceof Zend_View ) ;
        $this - > assertTrue ( is_array ( $scriptPath ) ) ;
        $this - > assertEquals (
            ’/ views / scripts / ’ , $scriptPath [0]
        );
   }




Eberlei (direkt effekt GmbH)   Unit-Testing Bad-Practices   IPC 09, Karlsruhe   12 / 47
ZF Controller Refactoring 3

   public function t e s t R e n d e r B y N a m e R e f a c t o r e d ()
   {
       // fixture setup
       $controller =
           $this - > c r e a teViewController ( ’ view ’ , ’ test ’) ;

        // execution
        $controller - > testAction () ;

        // assertions
        $this - > assertContains (
            ’ In the index action view ’ ,
            $response - > getBody ()
        );
   }




Eberlei (direkt effekt GmbH)   Unit-Testing Bad-Practices   IPC 09, Karlsruhe   13 / 47
Assertion Roulette




Eberlei (direkt effekt GmbH)   Unit-Testing Bad-Practices   IPC 09, Karlsruhe   14 / 47
Doctrine ResultSetMapping

   public function t e s t B a s i c Re s u l t S e t M a p p i n g ()
   {
       // Fixture Setup
       $rsm = new ResultSetMapping () ;
       $rsm - > addEntityResult (
            ’ Doctrine  Tests  Models  CMS  CmsUser ’ ,
            ’u ’
       );
       $rsm - > addFieldResult ( ’u ’ , ’ id ’ , ’ id ’) ;
       $rsm - > addFieldResult ( ’u ’ , ’ status ’ , ’ status ’) ;
       $rsm - > addFieldResult ( ’u ’ , ’ user ’ , ’ user ’) ;
       $rsm - > addFieldResult ( ’u ’ , ’ name ’ , ’ name ’) ;
       // [..]
   }




Eberlei (direkt effekt GmbH)   Unit-Testing Bad-Practices   IPC 09, Karlsruhe   15 / 47
Doctrine ResultSetMapping 2
   public function t e s t B a s i c Re s u l t S e t M a p p i n g ()
   {
       // [..]
       $this - > assertFalse ( $rsm - > isScalarResult ( ’ id ’) ) ;
       $this - > assertFalse ( $rsm - > isScalarResult ( ’ status ’) ) ;
       $this - > assertFalse ( $rsm - > isScalarResult ( ’ user ’) ) ;
       $this - > assertFalse ( $rsm - > isScalarResult ( ’ name ’) ) ;

        $this - > assertTrue (
            $rsm - > getClass ( ’u ’) ==
            ’ Doctrine  Tests  Models  CMS  CmsUser ’
        );
        $class = $rsm - > getOwningClass ( ’ id ’) ;
        $this - > assertTrue (
            $class == ’ Doctrine  Tests  Models  CMS  CmsUser ’
        );
   }




Eberlei (direkt effekt GmbH)   Unit-Testing Bad-Practices   IPC 09, Karlsruhe   16 / 47
Doctrine ResultSetMapping 3

   public function t e s t B a s i c Re s u l t S e t M a p p i n g ()
   {
     // [..]
     $this - > assertEquals ( ’u ’ , $rsm - > getAlias ( ’ id ’) ) ;
     $this - > assertEquals ( ’u ’ , $rsm - > getAlias ( ’ status ’) ) ;
     $this - > assertEquals ( ’u ’ , $rsm - > getAlias ( ’ user ’) ) ;
     $this - > assertEquals ( ’u ’ , $rsm - > getAlias ( ’ name ’) ) ;

       $this - > assertEquals ( ’ id ’ , $rsm - > getField ( ’ id ’) ) ;
       $this - > assertEquals ( ’ status ’ , $rsm - > getField ( ’ status ’) ) ;
       $this - > assertEquals ( ’ username ’ , $rsm - > getField ( ’ user ’) ) ;
       $this - > assertEquals ( ’ name ’ , $rsm - > getField ( ’ name ’) ) ;
   }




Eberlei (direkt effekt GmbH)   Unit-Testing Bad-Practices   IPC 09, Karlsruhe   17 / 47
Eager Test




Eberlei (direkt effekt GmbH)   Unit-Testing Bad-Practices   IPC 09, Karlsruhe   18 / 47
ezcUrl Test

   public function t e s t R e m o v e O r d e r e d P a r a m e t e r ()
   {
       $urlCfg = new e zcUrlConfiguration () ;
       $urlCfg - > a d dO r d eredParameter ( ’ section ’ ) ;
       $urlCfg - > a d dO r d eredParameter ( ’ module ’ ) ;
       $urlCfg - > a d dO r d eredParameter ( ’ view ’ ) ;

         $u = ’ http :// www . example . com / doc / components ’;
         $url = new ezcUrl ( $u , $urlCfg ) ;

         // [..]
   }




Eberlei (direkt effekt GmbH)      Unit-Testing Bad-Practices    IPC 09, Karlsruhe   19 / 47
ezcUrl Test 2
   public function t e s t R e m o v e O r d e r e d P a r a m e t e r ()
   {
       // [..]

         // functionality tested in other tests before
         $this - > assertEquals (
             array ( ’ section ’ = > 0 , ’ module ’ = > 1 , ’ view ’ = > 2) ,
             $url - > configuration - > orderedParameters
         );
         $this - > assertEquals ( ’ doc ’ , $url - > getParam ( ’ section ’) ) ;
         $this - > assertEquals (
             ’ components ’ , $url - > getParam ( ’ module ’)
         );

         // [..]
   }




Eberlei (direkt effekt GmbH)        Unit-Testing Bad-Practices     IPC 09, Karlsruhe   20 / 47
ezcUrl Test 3

   public function t e s t R e m o v e O r d e r e d P a r a m e t e r ()
   {
       // [..]
         // Primary Assertion according to test method name
         $url - > configuration - > r em ove Or de re dPa ra me ter ( ’ view ’) ;
         $this - > assertEquals (
              array ( ’ section ’ = > 0 , ’ module ’ = > 1 ) ,
              $url - > configuration - > orderedParameters
         );

         // [..]?
   }




Eberlei (direkt effekt GmbH)        Unit-Testing Bad-Practices     IPC 09, Karlsruhe   21 / 47
ezcUrl Test 4

   public function t e s t R e m o v e O r d e r e d P a r a m e t e r ()
   {
       // [..]
         try
         {
             $this - > assertEquals ( null , $url - > getParam ( ’ view ’) ) ;
             $this - > fail ( ’ Expected exception was not thrown . ’) ;
         } catch ( e z c U r l I n v a l i d P a r a m e t e r E x c e p t i o n $e ) {
             $expected = " ... " ;
             $this - > assertEquals ( $expected , $e - > getMessage () ) ;
         }

         // [..]?
   }




Eberlei (direkt effekt GmbH)        Unit-Testing Bad-Practices     IPC 09, Karlsruhe   22 / 47
ezcUrl Test 5

   public function t e s t R e m o v e O r d e r e d P a r a m e t e r ()
   {
       // [..]
         // try removing again - nothing bad should happen
         $url - > configuration - > r em ove Or de re dPa ra me ter ( ’ view ’) ;
         try
         {
              $this - > assertEquals ( null , $url - > getParam ( ’ view ’) ) ;
              $this - > fail ( ’ Expected exception was not thrown . ’) ;
         } catch ( e z c U r l I n v a l i d P a r a m e t e r E x c e p t i o n $e ) {
              $expected = " ... " ;
              $this - > assertEquals ( $expected , $e - > getMessage () ) ;
         }
   }




Eberlei (direkt effekt GmbH)        Unit-Testing Bad-Practices     IPC 09, Karlsruhe   23 / 47
Fragile Test




Eberlei (direkt effekt GmbH)   Unit-Testing Bad-Practices   IPC 09, Karlsruhe   24 / 47
Zend SOAP Wsdl Test
   function testAddBinding () {
    $wsdl = new Zend_Soap_Wsdl (
       ’ MyService ’ , ’ http :// localhost / MyService . php ’) ;
    $wsdl - > addPortType ( ’ myPortType ’) ;
    $wsdl - > addBinding ( ’ MyServiceBinding ’ , ’ myPortType ’) ;

       $this - > assertEquals ( $wsdl - > toXml () ) ,
        ’ <? xml version ="1.0"? > ’ .
        ’ < definitions xmlns =" http :// schemas . xmlsoap . org / wsdl /" ’
        . ’ xmlns : tns =" http :// localhost / MyService . php " ’
        . ’ xmlns : soap =" http :// schemas . xmlsoap . org / wsdl / soap /" ’
        . ’ xmlns : xsd =" http :// www . w3 . org /2001/ XMLSchema " ’
        . ’ xmlns : soap - enc =" http :// schemas . xmlsoap . org / soap /
              encoding /" ’
        . ’ xmlns : wsdl =" http :// schemas . xmlsoap . org / wsdl /" ’
        . ’ name =" MyService " targetNamespace =" http :// localhost /
              MyService . php " > ’
        . ’ < portType name =" myPortType "/ > ’
        . ’ < binding name =" MyServiceBinding " type =" myPortType "/ > ’
       . ’ </ definitions > ’ ) ;
   }


Eberlei (direkt effekt GmbH)    Unit-Testing Bad-Practices   IPC 09, Karlsruhe   25 / 47
Obscure Tests




Eberlei (direkt effekt GmbH)   Unit-Testing Bad-Practices   IPC 09, Karlsruhe   26 / 47
Global State: Zend Framework
   // Z e n d _ C o n t r o l l e r _ A c t i o n _ H e l p e r _ V i e w R e n d e r e r T e s t
   protected function setUp ()
   {
        $this - > request = new Z e n d _ C o n t r o l l e r _ R e q u e s t _ H t t p () ;
        $this - > response = new Z e n d _ C o n t r o l l e r _ R e s p o n s e _ H t t p () ;
        $this - > front                 = Ze nd_C ontro ller _Fron t :: getInstance ()
               ;
        $this - > front - > resetInstance () ;
        $this - > front - > a ddModuleDirectory ( ’/ _files / modules ’)
                                -> setRequest ( $this - > request )
                                -> setResponse ( $this - > response ) ;

         $this - > helper = new
                Z e n d _ C o n t r o l l e r _ A c t i o n _ H e l p e r _ V i e w R e n d e r e r () ;
         Z e n d _ C o n t r o l l e r _ A c t i o n _ H e l p e r B r o k e r :: addHelper (
                 $this - > helper
         );
   }




Eberlei (direkt effekt GmbH)             Unit-Testing Bad-Practices            IPC 09, Karlsruhe            27 / 47
Indirect Tests: ezcMvc
   function t e s t I n t e r n alRedirect () {
       $config = new s impleConfiguration () ;
       $config - > route = ’ IRController ’;
       $dispatcher = new e z c M v c C o n f i g u r a b l e D i s p a t c h e r (
           $config ) ;
       $dispatcher - > run () ;
       self :: assertEquals ( " BODY : Name : name , " .
            " Vars : array ([ CR ] ’ nonRedirVar ’ = > 4 , " .
            " [ CR ] ’ ReqRedirVar ’ = > 4 ,[ CR ]) " , $config - > store ) ;
   }

   function t e s t E x t e r n alRedirect () {
       $config = new s impleConfiguration () ;
       $config - > route = ’ IRController ’;
       $dispatcher = new e z c M v c C o n f i g u r a b l e D i s p a t c h e r (
           $config ) ;
       $dispatcher - > run () ;
       self :: assertEquals ( " BODY : Name : name , " .
            " Vars : array ([ CR ] ’ nonRedirVar ’ = > 4 , " .
            " [ CR ] ’ ReqRedirVar ’ = > 4 ,[ CR ]) " , $config - > store ) ;
   }


Eberlei (direkt effekt GmbH)   Unit-Testing Bad-Practices   IPC 09, Karlsruhe   28 / 47
Test-Names: FLOW3 MVC
          dispatchCallsTheControllersProcess
          RequestMethodUntilTheIsDispatchedFlag
          InTheRequestObjectIsSet()
          dispatchThrowsAnInfiniteLoopException
          IfTheRequestCouldNotBeDispached
          After99Iterations()
          resolveControllerReturnsTheNotFound
          ControllerDefinedInTheFLOW3Settings
          AndInjectsCorrectException
          IfTheResolvedControllerDoesNotExist()

Eberlei (direkt effekt GmbH)   Unit-Testing Bad-Practices   IPC 09, Karlsruhe   29 / 47
Test-Names: eZ Workflow
          testProperties()




Eberlei (direkt effekt GmbH)   Unit-Testing Bad-Practices   IPC 09, Karlsruhe   30 / 47
Test-Names: eZ Workflow
          testProperties()
          testProperties2()
          testProperties3()
          testProperties4()
          testProperties5()
          testProperties6()
          testProperties7()

Eberlei (direkt effekt GmbH)   Unit-Testing Bad-Practices   IPC 09, Karlsruhe   30 / 47
Slow Tests




Eberlei (direkt effekt GmbH)   Unit-Testing Bad-Practices   IPC 09, Karlsruhe   31 / 47
Zend Service Amazon
   public function setUp ()
   {
       $this - > _amazon = new Zend_Service_Amazon () ;
       $this - > _query = new Z e n d _ S e r v i ce _ A m a z o n _ Q u e r y ()

         $this - > _httpClient =
             new Z e n d _ H t t p _ C l i e n t _ A d a p t e r _ S o c k e t () ;
         $this - > _amazon - > getRestClient ()
                               -> getHttpClient ()
                               -> setAdapter ( $this - > _httpClient ) ;

         // terms of use compliance :
         // no more than one query per second
         sleep (1) ;
   }




Eberlei (direkt effekt GmbH)          Unit-Testing Bad-Practices        IPC 09, Karlsruhe   32 / 47
Zend Service Amazon 2

   public function t e s t I t e m S ea r c h M u s i c M o z a r t ()
   {
       $resultSet = $this - > _amazon - > itemSearch ( array (
           ’ SearchIndex ’         = > ’ Music ’ ,
           ’ Keywords ’            = > ’ Mozart ’ ,
           ’ ResponseGroup ’ = > ’ Small , Tracks , Offers ’
       ));
        foreach ( $resultSet as $item ) {
            $this - > assertTrue (
                $item instanceof Z e n d_ S e r vi c e _ Am a z o n_ I t e m
            );
        }
   }




Eberlei (direkt effekt GmbH)   Unit-Testing Bad-Practices   IPC 09, Karlsruhe   33 / 47
Zend Amazon Refactored

   public function setUpRefactored ()
   {
       $this - > _amazon = new Zend_Service_Amazon () ;

        $this - > _httpClient =
            new Z e n d _ H t t p _ C l i e n t _ A d a p t e r _ T e s t () ;

        $this - > _amazon - > getRestClient ()
                              -> getHttpClient ()
                              -> setAdapter ( $this - > _httpClient ) ;
   }




Eberlei (direkt effekt GmbH)         Unit-Testing Bad-Practices        IPC 09, Karlsruhe   34 / 47
Zend Amazon Refactored 2
   public function t e s t I t e m S e a r c h M u s i c M o z a r t R e f a c t o r e d ()
   {
       $this - > _httpClient - > setResponse (
           fil e_get_ contents ( " ExpectedTestResponse . txt " )
       );

         $resultSet = $this - > _amazon - > itemSearch ( array (
             ’ SearchIndex ’    = > ’ Music ’ ,
             ’ Keywords ’       = > ’ Mozart ’ ,
             ’ ResponseGroup ’ = > ’ Small , Tracks , Offers ’
         ));

         foreach ( $resultSet as $item ) {
             $this - > assertTrue (
                 $item instanceof Z e n d_ S e r vi c e _ Am a z o n_ I t e m
             );
             // Assert some relevant stuff now !
         }
   }



Eberlei (direkt effekt GmbH)         Unit-Testing Bad-Practices      IPC 09, Karlsruhe         35 / 47
Conditional Logic

          “Everyone knows that debugging is
          twice as hard as writing a program in
          the first place. So if you’re as clever as
          you can be when you write it, how will
          you ever debug it?” (Brian Kernighan)



Eberlei (direkt effekt GmbH)   Unit-Testing Bad-Practices   IPC 09, Karlsruhe   36 / 47
FLOW3 Cache Frontend
   public function t h e C o n s t r u c t o r A c c e p t s V a l i d I d e n t i f i e r s () {
       $mockBackend = $this - > createMockBackend () ;
         $identifiers = array (
             ’x ’ , ’ someValue ’ , ’ 123 fivesixseveneight ’ ,
             ’ some & ’ , ’ ab_cd % ’ ,
             rawurlencode ( ’ package :// some /      $ &% sadf ’) ,
             str_repeat ( ’x ’ , 250)
         );

         foreach ( $identifiers as $identifier ) {
             $abstractCache = $this - > getMock (
                 ’ F3  FLOW3  Cache  Frontend  StringFrontend ’ ,
                 array () ,
                 array ( $identifier , $mockBackend )
             );
         }
   }




Eberlei (direkt effekt GmbH)         Unit-Testing Bad-Practices      IPC 09, Karlsruhe        37 / 47
FLOW3 Cache Refactored
   /* *
    * @dataProvider d a t a A c c e p t V a l i d I d e n t i f ie r
    */
   public function c o n s t r u c t o r A c c e p t s V a l i d I d e n t i f i e r ( $id ) {
        $mockBackend = $this - > createMockBackend () ;

         $abstractCache = $this - > getMock (
             ’ F3  FLOW3  Cache  Frontend  StringFrontend ’ ,
             array () ,
             array ( $id , $mockBackend )
         );
   }
   static public function d a t a A c c e p tV a l i d I d e n t i f i e r () {
       return array (
           array ( ’x ’) , array ( ’ someValue ’) ,
           array ( ’ 123 fivesixseveneight ’) ,
           array ( ’ some & ’) , array ( ’ ab_cd % ’) ,
           array (
               rawurlencode ( ’ package :// some /                     $ &% sadf ’)
           ),
           array ( str_repeat ( ’x ’ , 250) )
       );
   }
Eberlei (direkt effekt GmbH)        Unit-Testing Bad-Practices      IPC 09, Karlsruhe        38 / 47
Zend Server ReflectionClass

   public function testGetMethods ()
   {
       $r = new Z e n d _ S e r v e r _ R e f l e c t i o n _ C l a s s (
           new ReflectionClass ( ’ Ze nd_ Se rv er_ Re fl ect io n ’)
       );

        $methods = $r - > getMethods () ;
        $this - > assertTrue ( is_array ( $methods ) ) ;
        foreach ( $methods as $m ) {
            $this - > assertTrue (
                   $m instanceof Z e n d _ S e r v e r _ R e f l e c t i o n _ M e t h o d
            );
        }
   }




Eberlei (direkt effekt GmbH)      Unit-Testing Bad-Practices      IPC 09, Karlsruhe       39 / 47
A working implementation

   class Z e n d _ S e r v e r _ R e f l e c t i o n _ C l a s s
   {
       public function getMethods ()
       {
             return array () ;
       }
   }


  Great, all tests pass!



Eberlei (direkt effekt GmbH)            Unit-Testing Bad-Practices   IPC 09, Karlsruhe   40 / 47
Zend Server ReflectionClass
Test Refactoring
   public function t e s t G e tM e t ho d s R ef a c t or e d ()
   {
       $r = new Z e n d _ S e r v e r _ R e f l e c t i o n _ C l a s s (
           new ReflectionClass ( ’ Ze nd_ Se rv er_ Re fl ect io n ’)
       );

        $methods = $r - > getMethods () ;
        $this - > assertTrue ( is_array ( $methods ) ) ;
        $this - > assertEquals (3 , count ( $methods ) ) ; // (!!)
        foreach ( $methods as $m ) {
            $this - > assertTrue (
                   $m instanceof Z e n d _ S e r v e r _ R e f l e c t i o n _ M e t h o d
            );
        }
   }




Eberlei (direkt effekt GmbH)      Unit-Testing Bad-Practices      IPC 09, Karlsruhe       41 / 47
Zend Server ReflectionClass
Test Refactoring 2
   public function ass ertReflMethods ( $methods , $expected )
   {
       $this - > assertTye ( ’ array ’ , $methods ) ;
       $this - > assertEquals ( $expected , count ( $methods ) ) ;
       foreach ( $methods as $m ) {
           $this - > assertTrue (
                  $m instanceof Z e n d _ S e r v e r _ R e f l e c t i o n _ M e t h o d
           );
       }
   }
   public function t e s t G e tM e t ho d s R ef a c t or e d ()
   {
       $r = new Z e n d _ S e r v e r _ R e f l e c t i o n _ C l a s s (
           new ReflectionClass ( ’ Ze nd_ Se rv er_ Re fl ect io n ’)
       );
       $this - > as sertRe flMethods ( $r - > getMethods () , 3) ;
   }


Eberlei (direkt effekt GmbH)       Unit-Testing Bad-Practices     IPC 09, Karlsruhe      42 / 47
Mock-Overkill




Eberlei (direkt effekt GmbH)   Unit-Testing Bad-Practices   IPC 09, Karlsruhe   43 / 47
FLOW3 MVC Dispatcher
   public function testDispatch () {
       $mockRequest = $this - > getMock ( ’ F3  FLOW3  MVC 
           RequestInterface ’) ;
       $mockRequest - > expects ( $this - > at (0) )
           -> method ( ’ isDispatched ’)
           -> will ( $this - > returnValue ( FALSE ) ) ;
       $mockRequest - > expects ( $this - > at (1) )
           -> method ( ’ isDispatched ’)
           -> will ( $this - > returnValue ( FALSE ) ) ;
       $mockRequest - > expects ( $this - > at (2) )
           -> method ( ’ isDispatched ’)
           -> will ( $this - > returnValue ( TRUE ) ) ;

        $mockResponse = $this - > getMock (
            ’ F3  FLOW3  MVC  ResponseInterface ’
        );

        // [..]
   }



Eberlei (direkt effekt GmbH)   Unit-Testing Bad-Practices   IPC 09, Karlsruhe   44 / 47
FLOW3 MVC Dispatcher 2
   public function testDispatch () {
       // [..]
       $mockController = $this - > getMock (
           ’ F3  FLOW3  MVC  Controller  ControllerInterface ’ ,
           array ( ’ processRequest ’ , ’ canProcessRequest ’)
       );
       $mockController - > expects ( $this - > exactly (2) )
           -> method ( ’ processRequest ’)
           -> with ( $mockRequest , $mockResponse ) ;
        $dispatcher = $this - > getMock (
            ’ F3  FLOW3  MVC  Dispatcher ’ , array ( ’
                  reso lveController ’) ,
            array () , ’ ’ , FALSE
        );
        $dispatcher - > expects ( $this - > any () )
                      -> method ( ’ resolveController ’)
                      -> will ( $this - > returnValue ( $mockController ) )
                            ;
        $dispatcher - > dispatch ( $mockRequest , $mockResponse ) ;
   }


Eberlei (direkt effekt GmbH)   Unit-Testing Bad-Practices   IPC 09, Karlsruhe   45 / 47
Further Readings
          xUnit Test Patterns
          Book by Gerald Meszaros, http://xunitpatterns.com/Test%20Smells.html


          TDD Anti Patterns
          http://blog.james-carr.org/2006/11/03/tdd-anti-patterns/


          Misko Hevery’s Blog
          http://misko.hevery.com/


          Google Testing Blog
          http://googletesting.blogspot.com/



Eberlei (direkt effekt GmbH)     Unit-Testing Bad-Practices    IPC 09, Karlsruhe   46 / 47
Thank You!

                 E-Mail: kontakt@beberlei.de
                       Twitter: beberlei
              Blog: http://www.whitewashing.de




Eberlei (direkt effekt GmbH)   Unit-Testing Bad-Practices   IPC 09, Karlsruhe   47 / 47

Contenu connexe

Tendances

Mocking Dependencies in PHPUnit
Mocking Dependencies in PHPUnitMocking Dependencies in PHPUnit
Mocking Dependencies in PHPUnitmfrost503
 
Unit testing with PHPUnit
Unit testing with PHPUnitUnit testing with PHPUnit
Unit testing with PHPUnitferca_sl
 
Oracle PL/SQL - Creative Conditional Compilation
Oracle PL/SQL - Creative Conditional CompilationOracle PL/SQL - Creative Conditional Compilation
Oracle PL/SQL - Creative Conditional CompilationScott Wesley
 
ISSTA 2010 Presentation
ISSTA 2010 PresentationISSTA 2010 Presentation
ISSTA 2010 PresentationJulian Dolby
 
SfCon: Test Driven Development
SfCon: Test Driven DevelopmentSfCon: Test Driven Development
SfCon: Test Driven DevelopmentAugusto Pascutti
 
Object-oriented Javascript
Object-oriented JavascriptObject-oriented Javascript
Object-oriented JavascriptDaniel Ku
 
Testing, Performance Analysis, and jQuery 1.4
Testing, Performance Analysis, and jQuery 1.4Testing, Performance Analysis, and jQuery 1.4
Testing, Performance Analysis, and jQuery 1.4jeresig
 
Min-Maxing Software Costs - Laracon EU 2015
Min-Maxing Software Costs - Laracon EU 2015Min-Maxing Software Costs - Laracon EU 2015
Min-Maxing Software Costs - Laracon EU 2015Konstantin Kudryashov
 
Code moi une RH! (PHP tour 2017)
Code moi une RH! (PHP tour 2017)Code moi une RH! (PHP tour 2017)
Code moi une RH! (PHP tour 2017)Arnaud Langlade
 
Feature Flags Are Flawed: Let's Make Them Better - DPC
Feature Flags Are Flawed: Let's Make Them Better - DPCFeature Flags Are Flawed: Let's Make Them Better - DPC
Feature Flags Are Flawed: Let's Make Them Better - DPCStephen Young
 
Why is crud a bad idea - focus on real scenarios
Why is crud a bad idea - focus on real scenariosWhy is crud a bad idea - focus on real scenarios
Why is crud a bad idea - focus on real scenariosDivante
 
code for quiz in my sql
code for quiz  in my sql code for quiz  in my sql
code for quiz in my sql JOYITAKUNDU1
 

Tendances (20)

Mocking Dependencies in PHPUnit
Mocking Dependencies in PHPUnitMocking Dependencies in PHPUnit
Mocking Dependencies in PHPUnit
 
Unit testing with PHPUnit
Unit testing with PHPUnitUnit testing with PHPUnit
Unit testing with PHPUnit
 
Oracle PL/SQL - Creative Conditional Compilation
Oracle PL/SQL - Creative Conditional CompilationOracle PL/SQL - Creative Conditional Compilation
Oracle PL/SQL - Creative Conditional Compilation
 
Stub you!
Stub you!Stub you!
Stub you!
 
Deep dive into Oracle ADF
Deep dive into Oracle ADFDeep dive into Oracle ADF
Deep dive into Oracle ADF
 
A Test of Strength
A Test of StrengthA Test of Strength
A Test of Strength
 
Hidden rocks in Oracle ADF
Hidden rocks in Oracle ADFHidden rocks in Oracle ADF
Hidden rocks in Oracle ADF
 
ISSTA 2010 Presentation
ISSTA 2010 PresentationISSTA 2010 Presentation
ISSTA 2010 Presentation
 
SfCon: Test Driven Development
SfCon: Test Driven DevelopmentSfCon: Test Driven Development
SfCon: Test Driven Development
 
Con5623 pdf 5623_001
Con5623 pdf 5623_001Con5623 pdf 5623_001
Con5623 pdf 5623_001
 
Object-oriented Javascript
Object-oriented JavascriptObject-oriented Javascript
Object-oriented Javascript
 
Min-Maxing Software Costs
Min-Maxing Software CostsMin-Maxing Software Costs
Min-Maxing Software Costs
 
Testing, Performance Analysis, and jQuery 1.4
Testing, Performance Analysis, and jQuery 1.4Testing, Performance Analysis, and jQuery 1.4
Testing, Performance Analysis, and jQuery 1.4
 
Min-Maxing Software Costs - Laracon EU 2015
Min-Maxing Software Costs - Laracon EU 2015Min-Maxing Software Costs - Laracon EU 2015
Min-Maxing Software Costs - Laracon EU 2015
 
Code moi une RH! (PHP tour 2017)
Code moi une RH! (PHP tour 2017)Code moi une RH! (PHP tour 2017)
Code moi une RH! (PHP tour 2017)
 
Feature Flags Are Flawed: Let's Make Them Better - DPC
Feature Flags Are Flawed: Let's Make Them Better - DPCFeature Flags Are Flawed: Let's Make Them Better - DPC
Feature Flags Are Flawed: Let's Make Them Better - DPC
 
AssertJ quick introduction
AssertJ quick introductionAssertJ quick introduction
AssertJ quick introduction
 
Calculon
CalculonCalculon
Calculon
 
Why is crud a bad idea - focus on real scenarios
Why is crud a bad idea - focus on real scenariosWhy is crud a bad idea - focus on real scenarios
Why is crud a bad idea - focus on real scenarios
 
code for quiz in my sql
code for quiz  in my sql code for quiz  in my sql
code for quiz in my sql
 

En vedette

User Testing by Example
User Testing by ExampleUser Testing by Example
User Testing by ExampleJeremy Horn
 
Specification by Example
Specification by ExampleSpecification by Example
Specification by ExampleSergey Shishkin
 
Unit-Testing Bad-Practices by Example
Unit-Testing Bad-Practices by ExampleUnit-Testing Bad-Practices by Example
Unit-Testing Bad-Practices by ExampleBenjamin Eberlei
 
Specifications For Enterprise Testing
Specifications For Enterprise TestingSpecifications For Enterprise Testing
Specifications For Enterprise TestingSathyan Sethumadhavan
 
7 1-1 soap-developers_guide
7 1-1 soap-developers_guide7 1-1 soap-developers_guide
7 1-1 soap-developers_guideNugroho Hermanto
 
Don't Drop the SOAP: Real World Web Service Testing for Web Hackers
Don't Drop the SOAP: Real World Web Service Testing for Web Hackers Don't Drop the SOAP: Real World Web Service Testing for Web Hackers
Don't Drop the SOAP: Real World Web Service Testing for Web Hackers Tom Eston
 
Moving Towards Zero Defects with Specification by Example
Moving Towards Zero Defects with Specification by ExampleMoving Towards Zero Defects with Specification by Example
Moving Towards Zero Defects with Specification by ExampleSteve Rogalsky
 
Types of Software Testing
Types of Software TestingTypes of Software Testing
Types of Software TestingNishant Worah
 
Testing concepts ppt
Testing concepts pptTesting concepts ppt
Testing concepts pptRathna Priya
 
Introduction to Agile software testing
Introduction to Agile software testingIntroduction to Agile software testing
Introduction to Agile software testingKMS Technology
 
Agile Testing Process
Agile Testing ProcessAgile Testing Process
Agile Testing ProcessIntetics
 
Software Testing Fundamentals
Software Testing FundamentalsSoftware Testing Fundamentals
Software Testing FundamentalsChankey Pathak
 
How I got 2.5 Million views on Slideshare (by @nickdemey - Board of Innovation)
How I got 2.5 Million views on Slideshare (by @nickdemey - Board of Innovation)How I got 2.5 Million views on Slideshare (by @nickdemey - Board of Innovation)
How I got 2.5 Million views on Slideshare (by @nickdemey - Board of Innovation)Board of Innovation
 

En vedette (20)

Domino testing presentation
Domino testing presentationDomino testing presentation
Domino testing presentation
 
User Testing by Example
User Testing by ExampleUser Testing by Example
User Testing by Example
 
Postgresql and ror
Postgresql and rorPostgresql and ror
Postgresql and ror
 
Specification by Example
Specification by ExampleSpecification by Example
Specification by Example
 
Unit-Testing Bad-Practices by Example
Unit-Testing Bad-Practices by ExampleUnit-Testing Bad-Practices by Example
Unit-Testing Bad-Practices by Example
 
Testing
TestingTesting
Testing
 
Specifications For Enterprise Testing
Specifications For Enterprise TestingSpecifications For Enterprise Testing
Specifications For Enterprise Testing
 
7 1-1 soap-developers_guide
7 1-1 soap-developers_guide7 1-1 soap-developers_guide
7 1-1 soap-developers_guide
 
Don't Drop the SOAP: Real World Web Service Testing for Web Hackers
Don't Drop the SOAP: Real World Web Service Testing for Web Hackers Don't Drop the SOAP: Real World Web Service Testing for Web Hackers
Don't Drop the SOAP: Real World Web Service Testing for Web Hackers
 
Moving Towards Zero Defects with Specification by Example
Moving Towards Zero Defects with Specification by ExampleMoving Towards Zero Defects with Specification by Example
Moving Towards Zero Defects with Specification by Example
 
Learn SoapUI
Learn SoapUILearn SoapUI
Learn SoapUI
 
Agile Testing by Example
Agile Testing by ExampleAgile Testing by Example
Agile Testing by Example
 
Manual testing ppt
Manual testing pptManual testing ppt
Manual testing ppt
 
Types of Software Testing
Types of Software TestingTypes of Software Testing
Types of Software Testing
 
Testing concepts ppt
Testing concepts pptTesting concepts ppt
Testing concepts ppt
 
Introduction to Agile software testing
Introduction to Agile software testingIntroduction to Agile software testing
Introduction to Agile software testing
 
Agile Testing Process
Agile Testing ProcessAgile Testing Process
Agile Testing Process
 
Software Testing Fundamentals
Software Testing FundamentalsSoftware Testing Fundamentals
Software Testing Fundamentals
 
The Minimum Loveable Product
The Minimum Loveable ProductThe Minimum Loveable Product
The Minimum Loveable Product
 
How I got 2.5 Million views on Slideshare (by @nickdemey - Board of Innovation)
How I got 2.5 Million views on Slideshare (by @nickdemey - Board of Innovation)How I got 2.5 Million views on Slideshare (by @nickdemey - Board of Innovation)
How I got 2.5 Million views on Slideshare (by @nickdemey - Board of Innovation)
 

Similaire à Unittesting Bad-Practices by Example

Test driven node.js
Test driven node.jsTest driven node.js
Test driven node.jsJay Harris
 
Php unit the-mostunknownparts
Php unit the-mostunknownpartsPhp unit the-mostunknownparts
Php unit the-mostunknownpartsBastian Feder
 
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 PHPUnitsmueller_sandsmedia
 
Component lifecycle hooks in Angular 2.0
Component lifecycle hooks in Angular 2.0Component lifecycle hooks in Angular 2.0
Component lifecycle hooks in Angular 2.0Eyal Vardi
 
node.js Module Development
node.js Module Developmentnode.js Module Development
node.js Module DevelopmentJay Harris
 
Testing Code and Assuring Quality
Testing Code and Assuring QualityTesting Code and Assuring Quality
Testing Code and Assuring QualityKent Cowgill
 
PHPunit and you
PHPunit and youPHPunit and you
PHPunit and youmarkstory
 
PHPUnit elevato alla Symfony2
PHPUnit elevato alla Symfony2PHPUnit elevato alla Symfony2
PHPUnit elevato alla Symfony2eugenio pombi
 
Php unit the-mostunknownparts
Php unit the-mostunknownpartsPhp unit the-mostunknownparts
Php unit the-mostunknownpartsBastian Feder
 
PhpUnit - The most unknown Parts
PhpUnit - The most unknown PartsPhpUnit - The most unknown Parts
PhpUnit - The most unknown PartsBastian Feder
 
Feature flagsareflawed
Feature flagsareflawedFeature flagsareflawed
Feature flagsareflawedStephen Young
 
DRUPAL 8 STORAGES OVERVIEW
DRUPAL 8 STORAGES OVERVIEWDRUPAL 8 STORAGES OVERVIEW
DRUPAL 8 STORAGES OVERVIEWDrupalCamp Kyiv
 
Feature Flags Are Flawed: Let's Make Them Better
Feature Flags Are Flawed: Let's Make Them BetterFeature Flags Are Flawed: Let's Make Them Better
Feature Flags Are Flawed: Let's Make Them BetterStephen Young
 
Symfony2, creare bundle e valore per il cliente
Symfony2, creare bundle e valore per il clienteSymfony2, creare bundle e valore per il cliente
Symfony2, creare bundle e valore per il clienteLeonardo Proietti
 
Refactoring using Codeception
Refactoring using CodeceptionRefactoring using Codeception
Refactoring using CodeceptionJeroen van Dijk
 

Similaire à Unittesting Bad-Practices by Example (20)

Test driven node.js
Test driven node.jsTest driven node.js
Test driven node.js
 
Php unit the-mostunknownparts
Php unit the-mostunknownpartsPhp unit the-mostunknownparts
Php unit the-mostunknownparts
 
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
 
Component lifecycle hooks in Angular 2.0
Component lifecycle hooks in Angular 2.0Component lifecycle hooks in Angular 2.0
Component lifecycle hooks in Angular 2.0
 
node.js Module Development
node.js Module Developmentnode.js Module Development
node.js Module Development
 
Testing Code and Assuring Quality
Testing Code and Assuring QualityTesting Code and Assuring Quality
Testing Code and Assuring Quality
 
Unittests für Dummies
Unittests für DummiesUnittests für Dummies
Unittests für Dummies
 
Mocking Demystified
Mocking DemystifiedMocking Demystified
Mocking Demystified
 
PHP Unit Testing
PHP Unit TestingPHP Unit Testing
PHP Unit Testing
 
PHPunit and you
PHPunit and youPHPunit and you
PHPunit and you
 
PHPUnit elevato alla Symfony2
PHPUnit elevato alla Symfony2PHPUnit elevato alla Symfony2
PHPUnit elevato alla Symfony2
 
Php unit the-mostunknownparts
Php unit the-mostunknownpartsPhp unit the-mostunknownparts
Php unit the-mostunknownparts
 
PhpUnit - The most unknown Parts
PhpUnit - The most unknown PartsPhpUnit - The most unknown Parts
PhpUnit - The most unknown Parts
 
Feature flagsareflawed
Feature flagsareflawedFeature flagsareflawed
Feature flagsareflawed
 
DRUPAL 8 STORAGES OVERVIEW
DRUPAL 8 STORAGES OVERVIEWDRUPAL 8 STORAGES OVERVIEW
DRUPAL 8 STORAGES OVERVIEW
 
Feature Flags Are Flawed: Let's Make Them Better
Feature Flags Are Flawed: Let's Make Them BetterFeature Flags Are Flawed: Let's Make Them Better
Feature Flags Are Flawed: Let's Make Them Better
 
Symfony2, creare bundle e valore per il cliente
Symfony2, creare bundle e valore per il clienteSymfony2, creare bundle e valore per il cliente
Symfony2, creare bundle e valore per il cliente
 
Refactoring using Codeception
Refactoring using CodeceptionRefactoring using Codeception
Refactoring using Codeception
 
PHPUnit testing to Zend_Test
PHPUnit testing to Zend_TestPHPUnit testing to Zend_Test
PHPUnit testing to Zend_Test
 
Test driven development_for_php
Test driven development_for_phpTest driven development_for_php
Test driven development_for_php
 

Plus de Benjamin Eberlei

Just Married: Zend Framework and Doctrine
Just Married: Zend Framework and DoctrineJust Married: Zend Framework and Doctrine
Just Married: Zend Framework and DoctrineBenjamin Eberlei
 
Towards the Cloud: Event-driven Architectures in PHP
Towards the Cloud: Event-driven Architectures in PHPTowards the Cloud: Event-driven Architectures in PHP
Towards the Cloud: Event-driven Architectures in PHPBenjamin Eberlei
 
Framework-Qualität: Tests als Gütesiegel
Framework-Qualität: Tests als GütesiegelFramework-Qualität: Tests als Gütesiegel
Framework-Qualität: Tests als GütesiegelBenjamin Eberlei
 

Plus de Benjamin Eberlei (6)

Introduction to Tideways
Introduction to TidewaysIntroduction to Tideways
Introduction to Tideways
 
Doctrine and NoSQL
Doctrine and NoSQLDoctrine and NoSQL
Doctrine and NoSQL
 
Doctrine for NoSQL
Doctrine for NoSQLDoctrine for NoSQL
Doctrine for NoSQL
 
Just Married: Zend Framework and Doctrine
Just Married: Zend Framework and DoctrineJust Married: Zend Framework and Doctrine
Just Married: Zend Framework and Doctrine
 
Towards the Cloud: Event-driven Architectures in PHP
Towards the Cloud: Event-driven Architectures in PHPTowards the Cloud: Event-driven Architectures in PHP
Towards the Cloud: Event-driven Architectures in PHP
 
Framework-Qualität: Tests als Gütesiegel
Framework-Qualität: Tests als GütesiegelFramework-Qualität: Tests als Gütesiegel
Framework-Qualität: Tests als Gütesiegel
 

Dernier

EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEarley Information Science
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdflior mazor
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
Evaluating the top large language models.pdf
Evaluating the top large language models.pdfEvaluating the top large language models.pdf
Evaluating the top large language models.pdfChristopherTHyatt
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Enterprise Knowledge
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUK Journal
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 

Dernier (20)

EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Evaluating the top large language models.pdf
Evaluating the top large language models.pdfEvaluating the top large language models.pdf
Evaluating the top large language models.pdf
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 

Unittesting Bad-Practices by Example

  • 1. Unit-Testing Bad-Practices by Example Benjamin Eberlei direkt effekt GmbH IPC 09, Karlsruhe Eberlei (direkt effekt GmbH) Unit-Testing Bad-Practices IPC 09, Karlsruhe 1 / 47
  • 2. About Me Benjamin Eberlei direkt effekt GmBH (digital marketing) Open Source contributor (Zend Framework and Doctrine 2) Twitter @beberlei Blog: www.whitewashing.de Eberlei (direkt effekt GmbH) Unit-Testing Bad-Practices IPC 09, Karlsruhe 2 / 47
  • 3. And You? Eberlei (direkt effekt GmbH) Unit-Testing Bad-Practices IPC 09, Karlsruhe 3 / 47
  • 4. Why Test Quality Matters Eberlei (direkt effekt GmbH) Unit-Testing Bad-Practices IPC 09, Karlsruhe 4 / 47
  • 5. “We spent 90% of the time modifying existing tests to acommodate for a relatively minor change.“ (G. Meszaros, xUnit Test Patterns) Eberlei (direkt effekt GmbH) Unit-Testing Bad-Practices IPC 09, Karlsruhe 5 / 47
  • 6. Safety Net vs Dead Weight Eberlei (direkt effekt GmbH) Unit-Testing Bad-Practices IPC 09, Karlsruhe 6 / 47
  • 7. Test Smells “Smell you later!” (Nelson, The Simpsons) Eberlei (direkt effekt GmbH) Unit-Testing Bad-Practices IPC 09, Karlsruhe 7 / 47
  • 8. Code Duplication Eberlei (direkt effekt GmbH) Unit-Testing Bad-Practices IPC 09, Karlsruhe 8 / 47
  • 9. ZF Controller Action public function testInitView () { Zen d_ C o n t r o l l e r _ Front :: getInstance () -> s e t C o n t r o l l er Dir ec to ry ( ’/ _files ’) ; require_once ’/ _files / ViewController . php ’; $controller = new ViewController ( new Z e n d _ C o n t r o l l e r _ R e q u e s t _ H t t p () , new Z e n d _ C o n t r o l l e r _ R e s p o n s e _ C l i () ); $view = $controller - > initView () ; $this - > assertTrue ( $view instanceof Zend_View ) ; $scriptPath = $view - > getScriptPaths () ; $this - > assertTrue ( is_array ( $scriptPath ) ) ; $this - > assertEquals ( ’/ views / scripts / ’ , $scriptPath [0]) ; } Eberlei (direkt effekt GmbH) Unit-Testing Bad-Practices IPC 09, Karlsruhe 9 / 47
  • 10. ZF Controller Action 2 public function testRenderByName () { $request = new Z e n d _ C o n t r o l l e r _ R e q u e s t _ H t t p () ; $request - > set ControllerName ( ’ view ’) -> setActionName ( ’ test ’) ; $response = new Z e n d _ C o n t r o l l e r _ R e s p o n s e _ C l i () ; Zen d_ C o n t r o l l e r _ Front :: getInstance () -> s e t C o n t r o l l er Dir ec to ry ( ’/ _files ’) ; require_once ’/ _files / ViewController . php ’; $controller = new ViewController ( $request , $response ) ; $controller - > testAction () ; $this - > assertContains ( ’ In the index action view ’ , $response - > getBody () ) ; } Eberlei (direkt effekt GmbH) Unit-Testing Bad-Practices IPC 09, Karlsruhe 10 / 47
  • 11. ZF Controller Refactoring Extract Test Utility Method: public function c r e ateViewController ( $controllerName = null , $actionName = null ) { $request = new Z e n d _ C o n t r o l l e r _ R e q u e s t _ H t t p () ; if ( $controllerName !== null ) { $request - > setControllerName ( $controllerName ) ; } if ( $actionName !== null ) { $request - > setActionName ( $actionName ) ; } $response = new Z e n d _ C o n t r o l l e r _ R e s p o n s e _ C l i () ; Zen d_ C o n t r o l l e r _ Front :: getInstance () -> s e t C o n t r o l le rD ire ct or y ( ’/ _files ’) ; require_once ’/ _files / ViewController . php ’; return new ViewController ( $request , $response ) ; } Eberlei (direkt effekt GmbH) Unit-Testing Bad-Practices IPC 09, Karlsruhe 11 / 47
  • 12. ZF Controller Refactoring 2 public function t e s tI nit Vi ew Ref ac to red () { // fixture setup $controller = $this - > createViewController () ; // execution $view = $controller - > initView () ; $scriptPath = $view - > getScriptPaths () ; // assertions $this - > assertTrue ( $view instanceof Zend_View ) ; $this - > assertTrue ( is_array ( $scriptPath ) ) ; $this - > assertEquals ( ’/ views / scripts / ’ , $scriptPath [0] ); } Eberlei (direkt effekt GmbH) Unit-Testing Bad-Practices IPC 09, Karlsruhe 12 / 47
  • 13. ZF Controller Refactoring 3 public function t e s t R e n d e r B y N a m e R e f a c t o r e d () { // fixture setup $controller = $this - > c r e a teViewController ( ’ view ’ , ’ test ’) ; // execution $controller - > testAction () ; // assertions $this - > assertContains ( ’ In the index action view ’ , $response - > getBody () ); } Eberlei (direkt effekt GmbH) Unit-Testing Bad-Practices IPC 09, Karlsruhe 13 / 47
  • 14. Assertion Roulette Eberlei (direkt effekt GmbH) Unit-Testing Bad-Practices IPC 09, Karlsruhe 14 / 47
  • 15. Doctrine ResultSetMapping public function t e s t B a s i c Re s u l t S e t M a p p i n g () { // Fixture Setup $rsm = new ResultSetMapping () ; $rsm - > addEntityResult ( ’ Doctrine Tests Models CMS CmsUser ’ , ’u ’ ); $rsm - > addFieldResult ( ’u ’ , ’ id ’ , ’ id ’) ; $rsm - > addFieldResult ( ’u ’ , ’ status ’ , ’ status ’) ; $rsm - > addFieldResult ( ’u ’ , ’ user ’ , ’ user ’) ; $rsm - > addFieldResult ( ’u ’ , ’ name ’ , ’ name ’) ; // [..] } Eberlei (direkt effekt GmbH) Unit-Testing Bad-Practices IPC 09, Karlsruhe 15 / 47
  • 16. Doctrine ResultSetMapping 2 public function t e s t B a s i c Re s u l t S e t M a p p i n g () { // [..] $this - > assertFalse ( $rsm - > isScalarResult ( ’ id ’) ) ; $this - > assertFalse ( $rsm - > isScalarResult ( ’ status ’) ) ; $this - > assertFalse ( $rsm - > isScalarResult ( ’ user ’) ) ; $this - > assertFalse ( $rsm - > isScalarResult ( ’ name ’) ) ; $this - > assertTrue ( $rsm - > getClass ( ’u ’) == ’ Doctrine Tests Models CMS CmsUser ’ ); $class = $rsm - > getOwningClass ( ’ id ’) ; $this - > assertTrue ( $class == ’ Doctrine Tests Models CMS CmsUser ’ ); } Eberlei (direkt effekt GmbH) Unit-Testing Bad-Practices IPC 09, Karlsruhe 16 / 47
  • 17. Doctrine ResultSetMapping 3 public function t e s t B a s i c Re s u l t S e t M a p p i n g () { // [..] $this - > assertEquals ( ’u ’ , $rsm - > getAlias ( ’ id ’) ) ; $this - > assertEquals ( ’u ’ , $rsm - > getAlias ( ’ status ’) ) ; $this - > assertEquals ( ’u ’ , $rsm - > getAlias ( ’ user ’) ) ; $this - > assertEquals ( ’u ’ , $rsm - > getAlias ( ’ name ’) ) ; $this - > assertEquals ( ’ id ’ , $rsm - > getField ( ’ id ’) ) ; $this - > assertEquals ( ’ status ’ , $rsm - > getField ( ’ status ’) ) ; $this - > assertEquals ( ’ username ’ , $rsm - > getField ( ’ user ’) ) ; $this - > assertEquals ( ’ name ’ , $rsm - > getField ( ’ name ’) ) ; } Eberlei (direkt effekt GmbH) Unit-Testing Bad-Practices IPC 09, Karlsruhe 17 / 47
  • 18. Eager Test Eberlei (direkt effekt GmbH) Unit-Testing Bad-Practices IPC 09, Karlsruhe 18 / 47
  • 19. ezcUrl Test public function t e s t R e m o v e O r d e r e d P a r a m e t e r () { $urlCfg = new e zcUrlConfiguration () ; $urlCfg - > a d dO r d eredParameter ( ’ section ’ ) ; $urlCfg - > a d dO r d eredParameter ( ’ module ’ ) ; $urlCfg - > a d dO r d eredParameter ( ’ view ’ ) ; $u = ’ http :// www . example . com / doc / components ’; $url = new ezcUrl ( $u , $urlCfg ) ; // [..] } Eberlei (direkt effekt GmbH) Unit-Testing Bad-Practices IPC 09, Karlsruhe 19 / 47
  • 20. ezcUrl Test 2 public function t e s t R e m o v e O r d e r e d P a r a m e t e r () { // [..] // functionality tested in other tests before $this - > assertEquals ( array ( ’ section ’ = > 0 , ’ module ’ = > 1 , ’ view ’ = > 2) , $url - > configuration - > orderedParameters ); $this - > assertEquals ( ’ doc ’ , $url - > getParam ( ’ section ’) ) ; $this - > assertEquals ( ’ components ’ , $url - > getParam ( ’ module ’) ); // [..] } Eberlei (direkt effekt GmbH) Unit-Testing Bad-Practices IPC 09, Karlsruhe 20 / 47
  • 21. ezcUrl Test 3 public function t e s t R e m o v e O r d e r e d P a r a m e t e r () { // [..] // Primary Assertion according to test method name $url - > configuration - > r em ove Or de re dPa ra me ter ( ’ view ’) ; $this - > assertEquals ( array ( ’ section ’ = > 0 , ’ module ’ = > 1 ) , $url - > configuration - > orderedParameters ); // [..]? } Eberlei (direkt effekt GmbH) Unit-Testing Bad-Practices IPC 09, Karlsruhe 21 / 47
  • 22. ezcUrl Test 4 public function t e s t R e m o v e O r d e r e d P a r a m e t e r () { // [..] try { $this - > assertEquals ( null , $url - > getParam ( ’ view ’) ) ; $this - > fail ( ’ Expected exception was not thrown . ’) ; } catch ( e z c U r l I n v a l i d P a r a m e t e r E x c e p t i o n $e ) { $expected = " ... " ; $this - > assertEquals ( $expected , $e - > getMessage () ) ; } // [..]? } Eberlei (direkt effekt GmbH) Unit-Testing Bad-Practices IPC 09, Karlsruhe 22 / 47
  • 23. ezcUrl Test 5 public function t e s t R e m o v e O r d e r e d P a r a m e t e r () { // [..] // try removing again - nothing bad should happen $url - > configuration - > r em ove Or de re dPa ra me ter ( ’ view ’) ; try { $this - > assertEquals ( null , $url - > getParam ( ’ view ’) ) ; $this - > fail ( ’ Expected exception was not thrown . ’) ; } catch ( e z c U r l I n v a l i d P a r a m e t e r E x c e p t i o n $e ) { $expected = " ... " ; $this - > assertEquals ( $expected , $e - > getMessage () ) ; } } Eberlei (direkt effekt GmbH) Unit-Testing Bad-Practices IPC 09, Karlsruhe 23 / 47
  • 24. Fragile Test Eberlei (direkt effekt GmbH) Unit-Testing Bad-Practices IPC 09, Karlsruhe 24 / 47
  • 25. Zend SOAP Wsdl Test function testAddBinding () { $wsdl = new Zend_Soap_Wsdl ( ’ MyService ’ , ’ http :// localhost / MyService . php ’) ; $wsdl - > addPortType ( ’ myPortType ’) ; $wsdl - > addBinding ( ’ MyServiceBinding ’ , ’ myPortType ’) ; $this - > assertEquals ( $wsdl - > toXml () ) , ’ <? xml version ="1.0"? > ’ . ’ < definitions xmlns =" http :// schemas . xmlsoap . org / wsdl /" ’ . ’ xmlns : tns =" http :// localhost / MyService . php " ’ . ’ xmlns : soap =" http :// schemas . xmlsoap . org / wsdl / soap /" ’ . ’ xmlns : xsd =" http :// www . w3 . org /2001/ XMLSchema " ’ . ’ xmlns : soap - enc =" http :// schemas . xmlsoap . org / soap / encoding /" ’ . ’ xmlns : wsdl =" http :// schemas . xmlsoap . org / wsdl /" ’ . ’ name =" MyService " targetNamespace =" http :// localhost / MyService . php " > ’ . ’ < portType name =" myPortType "/ > ’ . ’ < binding name =" MyServiceBinding " type =" myPortType "/ > ’ . ’ </ definitions > ’ ) ; } Eberlei (direkt effekt GmbH) Unit-Testing Bad-Practices IPC 09, Karlsruhe 25 / 47
  • 26. Obscure Tests Eberlei (direkt effekt GmbH) Unit-Testing Bad-Practices IPC 09, Karlsruhe 26 / 47
  • 27. Global State: Zend Framework // Z e n d _ C o n t r o l l e r _ A c t i o n _ H e l p e r _ V i e w R e n d e r e r T e s t protected function setUp () { $this - > request = new Z e n d _ C o n t r o l l e r _ R e q u e s t _ H t t p () ; $this - > response = new Z e n d _ C o n t r o l l e r _ R e s p o n s e _ H t t p () ; $this - > front = Ze nd_C ontro ller _Fron t :: getInstance () ; $this - > front - > resetInstance () ; $this - > front - > a ddModuleDirectory ( ’/ _files / modules ’) -> setRequest ( $this - > request ) -> setResponse ( $this - > response ) ; $this - > helper = new Z e n d _ C o n t r o l l e r _ A c t i o n _ H e l p e r _ V i e w R e n d e r e r () ; Z e n d _ C o n t r o l l e r _ A c t i o n _ H e l p e r B r o k e r :: addHelper ( $this - > helper ); } Eberlei (direkt effekt GmbH) Unit-Testing Bad-Practices IPC 09, Karlsruhe 27 / 47
  • 28. Indirect Tests: ezcMvc function t e s t I n t e r n alRedirect () { $config = new s impleConfiguration () ; $config - > route = ’ IRController ’; $dispatcher = new e z c M v c C o n f i g u r a b l e D i s p a t c h e r ( $config ) ; $dispatcher - > run () ; self :: assertEquals ( " BODY : Name : name , " . " Vars : array ([ CR ] ’ nonRedirVar ’ = > 4 , " . " [ CR ] ’ ReqRedirVar ’ = > 4 ,[ CR ]) " , $config - > store ) ; } function t e s t E x t e r n alRedirect () { $config = new s impleConfiguration () ; $config - > route = ’ IRController ’; $dispatcher = new e z c M v c C o n f i g u r a b l e D i s p a t c h e r ( $config ) ; $dispatcher - > run () ; self :: assertEquals ( " BODY : Name : name , " . " Vars : array ([ CR ] ’ nonRedirVar ’ = > 4 , " . " [ CR ] ’ ReqRedirVar ’ = > 4 ,[ CR ]) " , $config - > store ) ; } Eberlei (direkt effekt GmbH) Unit-Testing Bad-Practices IPC 09, Karlsruhe 28 / 47
  • 29. Test-Names: FLOW3 MVC dispatchCallsTheControllersProcess RequestMethodUntilTheIsDispatchedFlag InTheRequestObjectIsSet() dispatchThrowsAnInfiniteLoopException IfTheRequestCouldNotBeDispached After99Iterations() resolveControllerReturnsTheNotFound ControllerDefinedInTheFLOW3Settings AndInjectsCorrectException IfTheResolvedControllerDoesNotExist() Eberlei (direkt effekt GmbH) Unit-Testing Bad-Practices IPC 09, Karlsruhe 29 / 47
  • 30. Test-Names: eZ Workflow testProperties() Eberlei (direkt effekt GmbH) Unit-Testing Bad-Practices IPC 09, Karlsruhe 30 / 47
  • 31. Test-Names: eZ Workflow testProperties() testProperties2() testProperties3() testProperties4() testProperties5() testProperties6() testProperties7() Eberlei (direkt effekt GmbH) Unit-Testing Bad-Practices IPC 09, Karlsruhe 30 / 47
  • 32. Slow Tests Eberlei (direkt effekt GmbH) Unit-Testing Bad-Practices IPC 09, Karlsruhe 31 / 47
  • 33. Zend Service Amazon public function setUp () { $this - > _amazon = new Zend_Service_Amazon () ; $this - > _query = new Z e n d _ S e r v i ce _ A m a z o n _ Q u e r y () $this - > _httpClient = new Z e n d _ H t t p _ C l i e n t _ A d a p t e r _ S o c k e t () ; $this - > _amazon - > getRestClient () -> getHttpClient () -> setAdapter ( $this - > _httpClient ) ; // terms of use compliance : // no more than one query per second sleep (1) ; } Eberlei (direkt effekt GmbH) Unit-Testing Bad-Practices IPC 09, Karlsruhe 32 / 47
  • 34. Zend Service Amazon 2 public function t e s t I t e m S ea r c h M u s i c M o z a r t () { $resultSet = $this - > _amazon - > itemSearch ( array ( ’ SearchIndex ’ = > ’ Music ’ , ’ Keywords ’ = > ’ Mozart ’ , ’ ResponseGroup ’ = > ’ Small , Tracks , Offers ’ )); foreach ( $resultSet as $item ) { $this - > assertTrue ( $item instanceof Z e n d_ S e r vi c e _ Am a z o n_ I t e m ); } } Eberlei (direkt effekt GmbH) Unit-Testing Bad-Practices IPC 09, Karlsruhe 33 / 47
  • 35. Zend Amazon Refactored public function setUpRefactored () { $this - > _amazon = new Zend_Service_Amazon () ; $this - > _httpClient = new Z e n d _ H t t p _ C l i e n t _ A d a p t e r _ T e s t () ; $this - > _amazon - > getRestClient () -> getHttpClient () -> setAdapter ( $this - > _httpClient ) ; } Eberlei (direkt effekt GmbH) Unit-Testing Bad-Practices IPC 09, Karlsruhe 34 / 47
  • 36. Zend Amazon Refactored 2 public function t e s t I t e m S e a r c h M u s i c M o z a r t R e f a c t o r e d () { $this - > _httpClient - > setResponse ( fil e_get_ contents ( " ExpectedTestResponse . txt " ) ); $resultSet = $this - > _amazon - > itemSearch ( array ( ’ SearchIndex ’ = > ’ Music ’ , ’ Keywords ’ = > ’ Mozart ’ , ’ ResponseGroup ’ = > ’ Small , Tracks , Offers ’ )); foreach ( $resultSet as $item ) { $this - > assertTrue ( $item instanceof Z e n d_ S e r vi c e _ Am a z o n_ I t e m ); // Assert some relevant stuff now ! } } Eberlei (direkt effekt GmbH) Unit-Testing Bad-Practices IPC 09, Karlsruhe 35 / 47
  • 37. Conditional Logic “Everyone knows that debugging is twice as hard as writing a program in the first place. So if you’re as clever as you can be when you write it, how will you ever debug it?” (Brian Kernighan) Eberlei (direkt effekt GmbH) Unit-Testing Bad-Practices IPC 09, Karlsruhe 36 / 47
  • 38. FLOW3 Cache Frontend public function t h e C o n s t r u c t o r A c c e p t s V a l i d I d e n t i f i e r s () { $mockBackend = $this - > createMockBackend () ; $identifiers = array ( ’x ’ , ’ someValue ’ , ’ 123 fivesixseveneight ’ , ’ some & ’ , ’ ab_cd % ’ , rawurlencode ( ’ package :// some / $ &% sadf ’) , str_repeat ( ’x ’ , 250) ); foreach ( $identifiers as $identifier ) { $abstractCache = $this - > getMock ( ’ F3 FLOW3 Cache Frontend StringFrontend ’ , array () , array ( $identifier , $mockBackend ) ); } } Eberlei (direkt effekt GmbH) Unit-Testing Bad-Practices IPC 09, Karlsruhe 37 / 47
  • 39. FLOW3 Cache Refactored /* * * @dataProvider d a t a A c c e p t V a l i d I d e n t i f ie r */ public function c o n s t r u c t o r A c c e p t s V a l i d I d e n t i f i e r ( $id ) { $mockBackend = $this - > createMockBackend () ; $abstractCache = $this - > getMock ( ’ F3 FLOW3 Cache Frontend StringFrontend ’ , array () , array ( $id , $mockBackend ) ); } static public function d a t a A c c e p tV a l i d I d e n t i f i e r () { return array ( array ( ’x ’) , array ( ’ someValue ’) , array ( ’ 123 fivesixseveneight ’) , array ( ’ some & ’) , array ( ’ ab_cd % ’) , array ( rawurlencode ( ’ package :// some / $ &% sadf ’) ), array ( str_repeat ( ’x ’ , 250) ) ); } Eberlei (direkt effekt GmbH) Unit-Testing Bad-Practices IPC 09, Karlsruhe 38 / 47
  • 40. Zend Server ReflectionClass public function testGetMethods () { $r = new Z e n d _ S e r v e r _ R e f l e c t i o n _ C l a s s ( new ReflectionClass ( ’ Ze nd_ Se rv er_ Re fl ect io n ’) ); $methods = $r - > getMethods () ; $this - > assertTrue ( is_array ( $methods ) ) ; foreach ( $methods as $m ) { $this - > assertTrue ( $m instanceof Z e n d _ S e r v e r _ R e f l e c t i o n _ M e t h o d ); } } Eberlei (direkt effekt GmbH) Unit-Testing Bad-Practices IPC 09, Karlsruhe 39 / 47
  • 41. A working implementation class Z e n d _ S e r v e r _ R e f l e c t i o n _ C l a s s { public function getMethods () { return array () ; } } Great, all tests pass! Eberlei (direkt effekt GmbH) Unit-Testing Bad-Practices IPC 09, Karlsruhe 40 / 47
  • 42. Zend Server ReflectionClass Test Refactoring public function t e s t G e tM e t ho d s R ef a c t or e d () { $r = new Z e n d _ S e r v e r _ R e f l e c t i o n _ C l a s s ( new ReflectionClass ( ’ Ze nd_ Se rv er_ Re fl ect io n ’) ); $methods = $r - > getMethods () ; $this - > assertTrue ( is_array ( $methods ) ) ; $this - > assertEquals (3 , count ( $methods ) ) ; // (!!) foreach ( $methods as $m ) { $this - > assertTrue ( $m instanceof Z e n d _ S e r v e r _ R e f l e c t i o n _ M e t h o d ); } } Eberlei (direkt effekt GmbH) Unit-Testing Bad-Practices IPC 09, Karlsruhe 41 / 47
  • 43. Zend Server ReflectionClass Test Refactoring 2 public function ass ertReflMethods ( $methods , $expected ) { $this - > assertTye ( ’ array ’ , $methods ) ; $this - > assertEquals ( $expected , count ( $methods ) ) ; foreach ( $methods as $m ) { $this - > assertTrue ( $m instanceof Z e n d _ S e r v e r _ R e f l e c t i o n _ M e t h o d ); } } public function t e s t G e tM e t ho d s R ef a c t or e d () { $r = new Z e n d _ S e r v e r _ R e f l e c t i o n _ C l a s s ( new ReflectionClass ( ’ Ze nd_ Se rv er_ Re fl ect io n ’) ); $this - > as sertRe flMethods ( $r - > getMethods () , 3) ; } Eberlei (direkt effekt GmbH) Unit-Testing Bad-Practices IPC 09, Karlsruhe 42 / 47
  • 44. Mock-Overkill Eberlei (direkt effekt GmbH) Unit-Testing Bad-Practices IPC 09, Karlsruhe 43 / 47
  • 45. FLOW3 MVC Dispatcher public function testDispatch () { $mockRequest = $this - > getMock ( ’ F3 FLOW3 MVC RequestInterface ’) ; $mockRequest - > expects ( $this - > at (0) ) -> method ( ’ isDispatched ’) -> will ( $this - > returnValue ( FALSE ) ) ; $mockRequest - > expects ( $this - > at (1) ) -> method ( ’ isDispatched ’) -> will ( $this - > returnValue ( FALSE ) ) ; $mockRequest - > expects ( $this - > at (2) ) -> method ( ’ isDispatched ’) -> will ( $this - > returnValue ( TRUE ) ) ; $mockResponse = $this - > getMock ( ’ F3 FLOW3 MVC ResponseInterface ’ ); // [..] } Eberlei (direkt effekt GmbH) Unit-Testing Bad-Practices IPC 09, Karlsruhe 44 / 47
  • 46. FLOW3 MVC Dispatcher 2 public function testDispatch () { // [..] $mockController = $this - > getMock ( ’ F3 FLOW3 MVC Controller ControllerInterface ’ , array ( ’ processRequest ’ , ’ canProcessRequest ’) ); $mockController - > expects ( $this - > exactly (2) ) -> method ( ’ processRequest ’) -> with ( $mockRequest , $mockResponse ) ; $dispatcher = $this - > getMock ( ’ F3 FLOW3 MVC Dispatcher ’ , array ( ’ reso lveController ’) , array () , ’ ’ , FALSE ); $dispatcher - > expects ( $this - > any () ) -> method ( ’ resolveController ’) -> will ( $this - > returnValue ( $mockController ) ) ; $dispatcher - > dispatch ( $mockRequest , $mockResponse ) ; } Eberlei (direkt effekt GmbH) Unit-Testing Bad-Practices IPC 09, Karlsruhe 45 / 47
  • 47. Further Readings xUnit Test Patterns Book by Gerald Meszaros, http://xunitpatterns.com/Test%20Smells.html TDD Anti Patterns http://blog.james-carr.org/2006/11/03/tdd-anti-patterns/ Misko Hevery’s Blog http://misko.hevery.com/ Google Testing Blog http://googletesting.blogspot.com/ Eberlei (direkt effekt GmbH) Unit-Testing Bad-Practices IPC 09, Karlsruhe 46 / 47
  • 48. Thank You! E-Mail: kontakt@beberlei.de Twitter: beberlei Blog: http://www.whitewashing.de Eberlei (direkt effekt GmbH) Unit-Testing Bad-Practices IPC 09, Karlsruhe 47 / 47