SlideShare ist ein Scribd-Unternehmen logo
1 von 74
Downloaden Sie, um offline zu lesen
Testing untestable code
Testing untestable code

 About me

  Stephan Hochdörfer, bitExpert AG
  Department Manager Research Labs
  enjoying PHP since 1999
  S.Hochdoerfer@bitExpert.de
  @shochdoerfer
Testing untestable code

 No excuse for writing bad code!
Testing untestable code




 Not to freak out!
Testing untestable code




 Creativity matters!
Testing untestable code




     "There is no secret to writing tests,
       there are only secrets to write
               testable code!"
                          Miško Hevery
Testing untestable code

 What is „untestable Code“?
Testing untestable code




 1. Wrong object construction

         “new” is evil!
                          s
Testing untestable code



 2. Tight coupling
Testing untestable code




 No code reuse!
Testing untestable code




 No isolation → not testable!
Testing untestable code




 3. Uncertainty
Testing untestable code




       "...our test strategy requires us to
       have more control [...] of the sut."
      Gerard Meszaros, xUnit Test Patterns: Refactoring Test
                              Code
Testing untestable code

 In a perfect world...




                  Unittest
                   Unittest   SUT
                               SUT
Testing untestable code

 Legacy code is not perfect...


                                 Dependency
                                  Dependency

       Unittest
        Unittest          SUT
                           SUT


                                 Dependency
                                  Dependency
Testing untestable code
                                 ...
 Legacy code is not perfect...


                                 Dependency
                                  Dependency

       Unittest
        Unittest          SUT
                           SUT


                                 Dependency
                                  Dependency




                                  ...
Testing untestable code
                                 ...
 Legacy code is not perfect...


                                 Dependency
                                  Dependency

       Unittest
        Unittest          SUT
                           SUT


                                 Dependency
                                  Dependency




                                  ...
Testing untestable code

 How to get „testable“ code?
Testing untestable code

 How to get „testable“ code?




                   Refactoring
Testing untestable code




     "Before you start refactoring, check
     that you have a solid suite of tests."
                    Martin Fowler, Refactoring
Testing untestable code




 Hope? - Nope...
Testing untestable code

 Which path to take?
Testing untestable code

 Which path to take?




       Do not change existing code!
Testing untestable code

 Examples




 Object Construction   External resources   Language issues
Testing untestable code

 Object construction
 <?php
 class Car {
    private $Engine;

     public function __construct($sEngine) {
        $this->Engine = Engine::getByType($sEngine);
     }

 }
Testing untestable code

 Object construction - Autoload
 <?php
 function run_autoload($psClass) {
    $sFileToInclude = strtolower($psClass).'.php';
    if(strtolower($psClass) == 'engine') {
       $sFileToInclude = '/custom/mocks/'.
       $sFileToInclude;
    }
    include($sFileToInclude);
 }


 // Testcase
 spl_autoload_register('run_autoload');
 $oCar = new Car('Diesel');
Testing untestable code

 Object construction
 <?php
 include('Engine.php');

 class Car {
    private $Engine;

     public function __construct($sEngine) {
        $this->Engine = Engine::getByType($sEngine);
     }
 }
Testing untestable code

 Object construction - include_path
 <?php
 ini_set('include_path',
    '/custom/mocks/'.PATH_SEPARATOR.
    ini_get('include_path'));

 // Testcase
 include('car.php');

 $oCar = new Car('Diesel');
 echo $oCar->run();
Testing untestable code

 Object construction – Stream Wrapper
 <?php
 class CustomWrapper {
   private $_handler;

   function stream_open($path, $mode, $options,
 &$opened_path) {

         stream_wrapper_restore('file');
         // @TODO: modify $path before fopen
         $this->_handler = fopen($path, $mode);
         stream_wrapper_unregister('file');
         stream_wrapper_register('file', 'CustomWrapper');
         return true;
     }
 }
Testing untestable code

 Object construction – Stream Wrapper
 stream_wrapper_unregister('file');
 stream_wrapper_register('file', 'CustomWrapper');
Testing untestable code

 Object construction – Stream Wrapper
 <?php
 class CustomWrapper {
    private $_handler ;

     function stream_read( $count ) {
        $content = fread($this->_handler, $count );
        $content = str_replace ('Engine::getByType' ,
         ' Abstract Engine::get' , $content );
        return $content ;
     }
 }
Testing untestable code

 Object construction – Namespaces
 <?php
 class Car {
    private $Engine;

     public function __construct($sEngine) {
        $this->Engine = CarEngine::
           getByType($sEngine);
     }
 }
Testing untestable code

 External resources
Testing untestable code

 External resources



             Database     Webservice



            Filesystem    Mailserver
Testing untestable code

 External resources – Mock database
Testing untestable code

 External resources – Mock database




          Provide own implementation
Testing untestable code

 External resources – Mock database



                          ZF example:
          $db = new Custom_Db_Adapter(array());
          Zend_Db_Table::setDefaultAdapter($db);
Testing untestable code

 External resources – Mock database




 PHPUnit_Extensions_Database_TestCase
Testing untestable code

 External resources – Mock database




            Proxy for your SQL Server
Testing untestable code

 External resources – Mock webservice
Testing untestable code

 External resources – Mock webservice




          Provide own implementation
Testing untestable code

 External resources – Mock webservice




            Host redirect via /etc/hosts
Testing untestable code

 External resources – Mock filesystem
Testing untestable code

 External resources – Mock filesystem
 <?php

 // set up test environmemt
 vfsStream::setup('exampleDir');

 // create directory in test enviroment
 mkdir(vfsStream::url('exampleDir').'/sample/');

 // check if directory was created
 echo vfsStreamWrapper::getRoot()->hasChild('sample');
Testing untestable code

 External resources – Mock Mailserver
Testing untestable code

 External resources – Mock Mailserver




                Use fake mail server
Testing untestable code

 External resources – Mock Mailserver

 $ cat /etc/php5/php.ini | grep sendmail_path
 sendmail_path=/usr/local/bin/logmail

 $ cat /usr/local/bin/logmail
 cat >> /tmp/logmail.log
Testing untestable code

 Dealing with language issues
Testing untestable code

 Dealing with language issues




             Testing your privates?
Testing untestable code

 Dealing with language issues
 <?php
 class CustomWrapper {
    private $_handler;

     function stream_read($count) {
        $content = fread($this->_handler, $count);
        $content = str_replace(
           'private function',
           'public function',
           $content
        );
        return $content;
     }
Testing untestable code

 Dealing with language issues
 $myClass = new MyClass();

 $reflectionClass = new ReflectionClass('MyClass');
 $reflectionMethod = $reflectionClass->
                         getMethod('mydemo');
 $reflectionMethod->setAccessible(true);
 $reflectionMethod->invoke($myClass);
Testing untestable code

 Dealing with language issues




       Overwrite internal functions?
Testing untestable code

 Dealing with language issues




              pecl install runkit-0.9
Testing untestable code

 Dealing with language issues - Runkit
 <?php

 ini_set('runkit.internal_override', '1');

 runkit_function_redefine('mail','','return
 true;');

 ?>
Testing untestable code

 Dealing with language issues




       pecl install funcall-0.3.0alpha
Testing untestable code

 Dealing with language issues - Funcall
 <?php
 function my_func($arg1, $arg2) {
     return $arg1.$arg2;
 }

 function post_cb($args,$result,$process_time) {
   // return custom result based on $args
 }

 fc_add_post('my_func','post_cb');
 var_dump(my_func('php', 'c'));
Testing untestable code




 What else?
Testing untestable code

 What else?




           Generative Programming
Testing untestable code

 Generative Programming

                 Configuration
                  Configuration


                                                1 ... n
       Implementation
        Implementation             Generator
                                    Generator   Product
         components
          components                             Product



                    Generator
                     Generator
                    application
                     application
Testing untestable code

 Generative Programming

                 Configuration
                  Configuration

                                                Application
                                                 Application

       Implementation
        Implementation             Generator
                                    Generator
         components
          components


                                                Testcases
                                                 Testcases
                    Generator
                     Generator
                    application
                     application
Testing untestable code

 Generative Programming




        A frame is a data structure
       for representing knowledge.
Testing untestable code

 A Frame instance
 <?php
 class Car {
    private $Engine;

     public function __construct($sEngine) {
        $this->Engine = <!{Factory}!>::
           getByType($sEngine);
     }

 }
Testing untestable code

 The Frame controller

 public class MyFrameController extends
 SimpleFrameController {

    public void execute(Frame frame, FeatureConfig
 config) {
       if(config.hasFeature("unittest")) {
         frame.setSlot("Factory", "FactoryMock");
       }
       else {
         frame.setSlot("Factory", "EngineFactory");
       }
    }
 }
Testing untestable code

 Generated result - Testcase
 <?php
 class Car {
    private $Engine;

     public function __construct($sEngine) {
        $this->Engine = FactoryMock::
           getByType($sEngine);
     }

 }
Testing untestable code

 Generated result - Application
 <?php
 class Car {
    private $Engine;

     public function __construct($sEngine) {
        $this->Engine = EngineFactory::
           getByType($sEngine);
     }

 }
Testing untestable code

 What is possible?
Testing untestable code

 What is possible?




          Show / hide parts of the code
Testing untestable code

 What is possible?




         Change content of global vars!
Testing untestable code

 What is possible?




              Define pre- or postfixes!
Testing untestable code

 Is it worth it?
Testing untestable code

 Conclusions




         Change your mindset to write
                testable code!
Testing untestable code

 Conclusions




            PHP is a swiss-army knife.
                 Use it that way!
http://joind.in/3922
Testing untestable code

 Bildquellen

 http://www.flickr.com/photos/andresrueda/3452940751/
 http://www.flickr.com/photos/andresrueda/3455410635/

Weitere ähnliche Inhalte

Was ist angesagt?

Testing untestable Code - PFCongres 2010
Testing untestable Code - PFCongres 2010Testing untestable Code - PFCongres 2010
Testing untestable Code - PFCongres 2010
Stephan Hochdörfer
 
Real World Dependency Injection - PFCongres 2010
Real World Dependency Injection - PFCongres 2010Real World Dependency Injection - PFCongres 2010
Real World Dependency Injection - PFCongres 2010
Stephan Hochdörfer
 
Playing with Java Classes and Bytecode
Playing with Java Classes and BytecodePlaying with Java Classes and Bytecode
Playing with Java Classes and Bytecode
Yoav Avrahami
 
"Formal Verification in Java" by Shura Iline, Vladimir Ivanov @ JEEConf 2013,...
"Formal Verification in Java" by Shura Iline, Vladimir Ivanov @ JEEConf 2013,..."Formal Verification in Java" by Shura Iline, Vladimir Ivanov @ JEEConf 2013,...
"Formal Verification in Java" by Shura Iline, Vladimir Ivanov @ JEEConf 2013,...
Vladimir Ivanov
 
Google mock for dummies
Google mock for dummiesGoogle mock for dummies
Google mock for dummies
Harry Potter
 
Working Effectively With Legacy Perl Code
Working Effectively With Legacy Perl CodeWorking Effectively With Legacy Perl Code
Working Effectively With Legacy Perl Code
erikmsp
 

Was ist angesagt? (20)

Testing untestable Code - PFCongres 2010
Testing untestable Code - PFCongres 2010Testing untestable Code - PFCongres 2010
Testing untestable Code - PFCongres 2010
 
Real World Dependency Injection - PFCongres 2010
Real World Dependency Injection - PFCongres 2010Real World Dependency Injection - PFCongres 2010
Real World Dependency Injection - PFCongres 2010
 
Invoke dynamics
Invoke dynamicsInvoke dynamics
Invoke dynamics
 
Advanced java interview questions
Advanced java interview questionsAdvanced java interview questions
Advanced java interview questions
 
Playing with Java Classes and Bytecode
Playing with Java Classes and BytecodePlaying with Java Classes and Bytecode
Playing with Java Classes and Bytecode
 
Living With Legacy Code
Living With Legacy CodeLiving With Legacy Code
Living With Legacy Code
 
"Formal Verification in Java" by Shura Iline, Vladimir Ivanov @ JEEConf 2013,...
"Formal Verification in Java" by Shura Iline, Vladimir Ivanov @ JEEConf 2013,..."Formal Verification in Java" by Shura Iline, Vladimir Ivanov @ JEEConf 2013,...
"Formal Verification in Java" by Shura Iline, Vladimir Ivanov @ JEEConf 2013,...
 
Mastering Mock Objects - Advanced Unit Testing for Java
Mastering Mock Objects - Advanced Unit Testing for JavaMastering Mock Objects - Advanced Unit Testing for Java
Mastering Mock Objects - Advanced Unit Testing for Java
 
Testing Legacy Rails Apps
Testing Legacy Rails AppsTesting Legacy Rails Apps
Testing Legacy Rails Apps
 
Java Annotation Processing: A Beginner Walkthrough
Java Annotation Processing: A Beginner WalkthroughJava Annotation Processing: A Beginner Walkthrough
Java Annotation Processing: A Beginner Walkthrough
 
Working Effectively With Legacy Code
Working Effectively With Legacy CodeWorking Effectively With Legacy Code
Working Effectively With Legacy Code
 
Google mock for dummies
Google mock for dummiesGoogle mock for dummies
Google mock for dummies
 
Developer testing 101: Become a Testing Fanatic
Developer testing 101: Become a Testing FanaticDeveloper testing 101: Become a Testing Fanatic
Developer testing 101: Become a Testing Fanatic
 
Testing in-python-and-pytest-framework
Testing in-python-and-pytest-frameworkTesting in-python-and-pytest-framework
Testing in-python-and-pytest-framework
 
Working Effectively With Legacy Perl Code
Working Effectively With Legacy Perl CodeWorking Effectively With Legacy Perl Code
Working Effectively With Legacy Perl Code
 
Java reflection
Java reflectionJava reflection
Java reflection
 
Spring IO 2015 Spock Workshop
Spring IO 2015 Spock WorkshopSpring IO 2015 Spock Workshop
Spring IO 2015 Spock Workshop
 
Java object oriented programming - OOPS
Java object oriented programming - OOPSJava object oriented programming - OOPS
Java object oriented programming - OOPS
 
Refactoring
RefactoringRefactoring
Refactoring
 
TDD and the Legacy Code Black Hole
TDD and the Legacy Code Black HoleTDD and the Legacy Code Black Hole
TDD and the Legacy Code Black Hole
 

Andere mochten auch

Testing untestable code - PHPUGFFM 01/11
Testing untestable code - PHPUGFFM 01/11Testing untestable code - PHPUGFFM 01/11
Testing untestable code - PHPUGFFM 01/11
Stephan Hochdörfer
 
Testing untestable code - Herbstcampus12
Testing untestable code - Herbstcampus12Testing untestable code - Herbstcampus12
Testing untestable code - Herbstcampus12
Stephan Hochdörfer
 
Simplify your external dependency management - DPC11
Simplify your external dependency management - DPC11Simplify your external dependency management - DPC11
Simplify your external dependency management - DPC11
Stephan Hochdörfer
 
Facebook für PHP Entwickler - phpugffm
Facebook für PHP Entwickler - phpugffmFacebook für PHP Entwickler - phpugffm
Facebook für PHP Entwickler - phpugffm
Stephan Hochdörfer
 
Offline Strategies for HTML5 Web Applications - ipc13
Offline Strategies for HTML5 Web Applications - ipc13Offline Strategies for HTML5 Web Applications - ipc13
Offline Strategies for HTML5 Web Applications - ipc13
Stephan Hochdörfer
 
Phing for power users - frOSCon8
Phing for power users - frOSCon8Phing for power users - frOSCon8
Phing for power users - frOSCon8
Stephan Hochdörfer
 

Andere mochten auch (6)

Testing untestable code - PHPUGFFM 01/11
Testing untestable code - PHPUGFFM 01/11Testing untestable code - PHPUGFFM 01/11
Testing untestable code - PHPUGFFM 01/11
 
Testing untestable code - Herbstcampus12
Testing untestable code - Herbstcampus12Testing untestable code - Herbstcampus12
Testing untestable code - Herbstcampus12
 
Simplify your external dependency management - DPC11
Simplify your external dependency management - DPC11Simplify your external dependency management - DPC11
Simplify your external dependency management - DPC11
 
Facebook für PHP Entwickler - phpugffm
Facebook für PHP Entwickler - phpugffmFacebook für PHP Entwickler - phpugffm
Facebook für PHP Entwickler - phpugffm
 
Offline Strategies for HTML5 Web Applications - ipc13
Offline Strategies for HTML5 Web Applications - ipc13Offline Strategies for HTML5 Web Applications - ipc13
Offline Strategies for HTML5 Web Applications - ipc13
 
Phing for power users - frOSCon8
Phing for power users - frOSCon8Phing for power users - frOSCon8
Phing for power users - frOSCon8
 

Ähnlich wie Testing untestable code - phpconpl11

Ähnlich wie Testing untestable code - phpconpl11 (20)

Testing untestable code - IPC12
Testing untestable code - IPC12Testing untestable code - IPC12
Testing untestable code - IPC12
 
Automated infrastructure testing - by Ranjib Dey
Automated infrastructure testing - by Ranjib DeyAutomated infrastructure testing - by Ranjib Dey
Automated infrastructure testing - by Ranjib Dey
 
Automated Infrastructure Testing
Automated Infrastructure TestingAutomated Infrastructure Testing
Automated Infrastructure Testing
 
Unit tests & TDD
Unit tests & TDDUnit tests & TDD
Unit tests & TDD
 
Automated Infrastructure Testing - Ranjib Dey
Automated Infrastructure Testing - Ranjib DeyAutomated Infrastructure Testing - Ranjib Dey
Automated Infrastructure Testing - Ranjib Dey
 
Coding Naked 2023
Coding Naked 2023Coding Naked 2023
Coding Naked 2023
 
Extreme
ExtremeExtreme
Extreme
 
Test
TestTest
Test
 
Coding Naked
Coding NakedCoding Naked
Coding Naked
 
Unit Testing Android Applications
Unit Testing Android ApplicationsUnit Testing Android Applications
Unit Testing Android Applications
 
GlobalLogic Test Automation Online TechTalk “Test Driven Development as a Per...
GlobalLogic Test Automation Online TechTalk “Test Driven Development as a Per...GlobalLogic Test Automation Online TechTalk “Test Driven Development as a Per...
GlobalLogic Test Automation Online TechTalk “Test Driven Development as a Per...
 
Quick tour to front end unit testing using jasmine
Quick tour to front end unit testing using jasmineQuick tour to front end unit testing using jasmine
Quick tour to front end unit testing using jasmine
 
Bypass Security Checking with Frida
Bypass Security Checking with FridaBypass Security Checking with Frida
Bypass Security Checking with Frida
 
Unit test
Unit testUnit test
Unit test
 
Js fwdays unit tesing javascript(by Anna Khabibullina)
Js fwdays unit tesing javascript(by Anna Khabibullina)Js fwdays unit tesing javascript(by Anna Khabibullina)
Js fwdays unit tesing javascript(by Anna Khabibullina)
 
JS Frameworks Day April,26 of 2014
JS Frameworks Day April,26 of 2014JS Frameworks Day April,26 of 2014
JS Frameworks Day April,26 of 2014
 
ngCore
ngCorengCore
ngCore
 
TDD and mock objects
TDD and mock objectsTDD and mock objects
TDD and mock objects
 
2011-02-03 LA RubyConf Rails3 TDD Workshop
2011-02-03 LA RubyConf Rails3 TDD Workshop2011-02-03 LA RubyConf Rails3 TDD Workshop
2011-02-03 LA RubyConf Rails3 TDD Workshop
 
Gallio Crafting A Toolchain
Gallio Crafting A ToolchainGallio Crafting A Toolchain
Gallio Crafting A Toolchain
 

Mehr von Stephan Hochdörfer

Offline. Na und? Strategien für offlinefähige Applikationen in HTML5 - Herbst...
Offline. Na und? Strategien für offlinefähige Applikationen in HTML5 - Herbst...Offline. Na und? Strategien für offlinefähige Applikationen in HTML5 - Herbst...
Offline. Na und? Strategien für offlinefähige Applikationen in HTML5 - Herbst...
Stephan Hochdörfer
 
Offline strategies for HTML5 web applications - frOSCon8
Offline strategies for HTML5 web applications - frOSCon8Offline strategies for HTML5 web applications - frOSCon8
Offline strategies for HTML5 web applications - frOSCon8
Stephan Hochdörfer
 
Offline Strategies for HTML5 Web Applications - oscon13
Offline Strategies for HTML5 Web Applications - oscon13Offline Strategies for HTML5 Web Applications - oscon13
Offline Strategies for HTML5 Web Applications - oscon13
Stephan Hochdörfer
 
Real World Dependency Injection - oscon13
Real World Dependency Injection - oscon13Real World Dependency Injection - oscon13
Real World Dependency Injection - oscon13
Stephan Hochdörfer
 
Dependency Injection in PHP - dwx13
Dependency Injection in PHP - dwx13Dependency Injection in PHP - dwx13
Dependency Injection in PHP - dwx13
Stephan Hochdörfer
 
Offline Strategien für HTML5 Web Applikationen - dwx13
Offline Strategien für HTML5 Web Applikationen - dwx13 Offline Strategien für HTML5 Web Applikationen - dwx13
Offline Strategien für HTML5 Web Applikationen - dwx13
Stephan Hochdörfer
 
Your Business. Your Language. Your Code - dpc13
Your Business. Your Language. Your Code - dpc13Your Business. Your Language. Your Code - dpc13
Your Business. Your Language. Your Code - dpc13
Stephan Hochdörfer
 
Phing for power users - dpc_uncon13
Phing for power users - dpc_uncon13Phing for power users - dpc_uncon13
Phing for power users - dpc_uncon13
Stephan Hochdörfer
 
Offline-Strategien für HTML5 Web Applikationen - wmka
Offline-Strategien für HTML5 Web Applikationen - wmkaOffline-Strategien für HTML5 Web Applikationen - wmka
Offline-Strategien für HTML5 Web Applikationen - wmka
Stephan Hochdörfer
 
Offline-Strategien für HTML5 Web Applikationen - bedcon13
Offline-Strategien für HTML5 Web Applikationen - bedcon13Offline-Strategien für HTML5 Web Applikationen - bedcon13
Offline-Strategien für HTML5 Web Applikationen - bedcon13
Stephan Hochdörfer
 
Real World Dependency Injection - phpugffm13
Real World Dependency Injection - phpugffm13Real World Dependency Injection - phpugffm13
Real World Dependency Injection - phpugffm13
Stephan Hochdörfer
 
Offline strategies for HTML5 web applications - ConFoo13
Offline strategies for HTML5 web applications - ConFoo13Offline strategies for HTML5 web applications - ConFoo13
Offline strategies for HTML5 web applications - ConFoo13
Stephan Hochdörfer
 
Offline-Strategien für HTML5Web Applikationen - WMMRN12
Offline-Strategien für HTML5Web Applikationen - WMMRN12Offline-Strategien für HTML5Web Applikationen - WMMRN12
Offline-Strategien für HTML5Web Applikationen - WMMRN12
Stephan Hochdörfer
 
Offline strategies for HTML5 web applications - IPC12
Offline strategies for HTML5 web applications - IPC12Offline strategies for HTML5 web applications - IPC12
Offline strategies for HTML5 web applications - IPC12
Stephan Hochdörfer
 
Große Systeme, lose Kopplung, Spaß bei der Arbeit! - WDC12
Große Systeme, lose Kopplung, Spaß bei der Arbeit! - WDC12Große Systeme, lose Kopplung, Spaß bei der Arbeit! - WDC12
Große Systeme, lose Kopplung, Spaß bei der Arbeit! - WDC12
Stephan Hochdörfer
 
Offline strategies for HTML5 web applications - pfCongres2012
Offline strategies for HTML5 web applications - pfCongres2012Offline strategies for HTML5 web applications - pfCongres2012
Offline strategies for HTML5 web applications - pfCongres2012
Stephan Hochdörfer
 
Wie Software-Generatoren die Welt verändern können - Herbstcampus12
Wie Software-Generatoren die Welt verändern können - Herbstcampus12Wie Software-Generatoren die Welt verändern können - Herbstcampus12
Wie Software-Generatoren die Welt verändern können - Herbstcampus12
Stephan Hochdörfer
 
Introducing a Software Generator Framework - JAZOON12
Introducing a Software Generator Framework - JAZOON12Introducing a Software Generator Framework - JAZOON12
Introducing a Software Generator Framework - JAZOON12
Stephan Hochdörfer
 

Mehr von Stephan Hochdörfer (20)

Offline. Na und? Strategien für offlinefähige Applikationen in HTML5 - Herbst...
Offline. Na und? Strategien für offlinefähige Applikationen in HTML5 - Herbst...Offline. Na und? Strategien für offlinefähige Applikationen in HTML5 - Herbst...
Offline. Na und? Strategien für offlinefähige Applikationen in HTML5 - Herbst...
 
Offline strategies for HTML5 web applications - frOSCon8
Offline strategies for HTML5 web applications - frOSCon8Offline strategies for HTML5 web applications - frOSCon8
Offline strategies for HTML5 web applications - frOSCon8
 
Offline Strategies for HTML5 Web Applications - oscon13
Offline Strategies for HTML5 Web Applications - oscon13Offline Strategies for HTML5 Web Applications - oscon13
Offline Strategies for HTML5 Web Applications - oscon13
 
Real World Dependency Injection - oscon13
Real World Dependency Injection - oscon13Real World Dependency Injection - oscon13
Real World Dependency Injection - oscon13
 
Dependency Injection in PHP - dwx13
Dependency Injection in PHP - dwx13Dependency Injection in PHP - dwx13
Dependency Injection in PHP - dwx13
 
Offline Strategien für HTML5 Web Applikationen - dwx13
Offline Strategien für HTML5 Web Applikationen - dwx13 Offline Strategien für HTML5 Web Applikationen - dwx13
Offline Strategien für HTML5 Web Applikationen - dwx13
 
Your Business. Your Language. Your Code - dpc13
Your Business. Your Language. Your Code - dpc13Your Business. Your Language. Your Code - dpc13
Your Business. Your Language. Your Code - dpc13
 
Phing for power users - dpc_uncon13
Phing for power users - dpc_uncon13Phing for power users - dpc_uncon13
Phing for power users - dpc_uncon13
 
Offline-Strategien für HTML5 Web Applikationen - wmka
Offline-Strategien für HTML5 Web Applikationen - wmkaOffline-Strategien für HTML5 Web Applikationen - wmka
Offline-Strategien für HTML5 Web Applikationen - wmka
 
Offline-Strategien für HTML5 Web Applikationen - bedcon13
Offline-Strategien für HTML5 Web Applikationen - bedcon13Offline-Strategien für HTML5 Web Applikationen - bedcon13
Offline-Strategien für HTML5 Web Applikationen - bedcon13
 
Real World Dependency Injection - phpugffm13
Real World Dependency Injection - phpugffm13Real World Dependency Injection - phpugffm13
Real World Dependency Injection - phpugffm13
 
A Phing fairy tale - ConFoo13
A Phing fairy tale - ConFoo13A Phing fairy tale - ConFoo13
A Phing fairy tale - ConFoo13
 
Offline strategies for HTML5 web applications - ConFoo13
Offline strategies for HTML5 web applications - ConFoo13Offline strategies for HTML5 web applications - ConFoo13
Offline strategies for HTML5 web applications - ConFoo13
 
Offline-Strategien für HTML5Web Applikationen - WMMRN12
Offline-Strategien für HTML5Web Applikationen - WMMRN12Offline-Strategien für HTML5Web Applikationen - WMMRN12
Offline-Strategien für HTML5Web Applikationen - WMMRN12
 
Offline strategies for HTML5 web applications - IPC12
Offline strategies for HTML5 web applications - IPC12Offline strategies for HTML5 web applications - IPC12
Offline strategies for HTML5 web applications - IPC12
 
Große Systeme, lose Kopplung, Spaß bei der Arbeit! - WDC12
Große Systeme, lose Kopplung, Spaß bei der Arbeit! - WDC12Große Systeme, lose Kopplung, Spaß bei der Arbeit! - WDC12
Große Systeme, lose Kopplung, Spaß bei der Arbeit! - WDC12
 
Offline strategies for HTML5 web applications - pfCongres2012
Offline strategies for HTML5 web applications - pfCongres2012Offline strategies for HTML5 web applications - pfCongres2012
Offline strategies for HTML5 web applications - pfCongres2012
 
Wie Software-Generatoren die Welt verändern können - Herbstcampus12
Wie Software-Generatoren die Welt verändern können - Herbstcampus12Wie Software-Generatoren die Welt verändern können - Herbstcampus12
Wie Software-Generatoren die Welt verändern können - Herbstcampus12
 
Introducing a Software Generator Framework - JAZOON12
Introducing a Software Generator Framework - JAZOON12Introducing a Software Generator Framework - JAZOON12
Introducing a Software Generator Framework - JAZOON12
 
The state of DI - DPC12
The state of DI - DPC12The state of DI - DPC12
The state of DI - DPC12
 

Kürzlich hochgeladen

Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Victor Rentea
 

Kürzlich hochgeladen (20)

DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 
Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Vector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxVector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptx
 
Six Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal OntologySix Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal Ontology
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
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
 
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelMcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
 

Testing untestable code - phpconpl11

  • 2. Testing untestable code About me  Stephan Hochdörfer, bitExpert AG  Department Manager Research Labs  enjoying PHP since 1999  S.Hochdoerfer@bitExpert.de  @shochdoerfer
  • 3. Testing untestable code No excuse for writing bad code!
  • 4. Testing untestable code Not to freak out!
  • 5. Testing untestable code Creativity matters!
  • 6. Testing untestable code "There is no secret to writing tests, there are only secrets to write testable code!" Miško Hevery
  • 7. Testing untestable code What is „untestable Code“?
  • 8. Testing untestable code 1. Wrong object construction “new” is evil! s
  • 9. Testing untestable code 2. Tight coupling
  • 10. Testing untestable code No code reuse!
  • 11. Testing untestable code No isolation → not testable!
  • 12. Testing untestable code 3. Uncertainty
  • 13. Testing untestable code "...our test strategy requires us to have more control [...] of the sut." Gerard Meszaros, xUnit Test Patterns: Refactoring Test Code
  • 14. Testing untestable code In a perfect world... Unittest Unittest SUT SUT
  • 15. Testing untestable code Legacy code is not perfect... Dependency Dependency Unittest Unittest SUT SUT Dependency Dependency
  • 16. Testing untestable code ... Legacy code is not perfect... Dependency Dependency Unittest Unittest SUT SUT Dependency Dependency ...
  • 17. Testing untestable code ... Legacy code is not perfect... Dependency Dependency Unittest Unittest SUT SUT Dependency Dependency ...
  • 18. Testing untestable code How to get „testable“ code?
  • 19. Testing untestable code How to get „testable“ code? Refactoring
  • 20. Testing untestable code "Before you start refactoring, check that you have a solid suite of tests." Martin Fowler, Refactoring
  • 21. Testing untestable code Hope? - Nope...
  • 22. Testing untestable code Which path to take?
  • 23. Testing untestable code Which path to take? Do not change existing code!
  • 24. Testing untestable code Examples Object Construction External resources Language issues
  • 25. Testing untestable code Object construction <?php class Car { private $Engine; public function __construct($sEngine) { $this->Engine = Engine::getByType($sEngine); } }
  • 26. Testing untestable code Object construction - Autoload <?php function run_autoload($psClass) { $sFileToInclude = strtolower($psClass).'.php'; if(strtolower($psClass) == 'engine') { $sFileToInclude = '/custom/mocks/'. $sFileToInclude; } include($sFileToInclude); } // Testcase spl_autoload_register('run_autoload'); $oCar = new Car('Diesel');
  • 27. Testing untestable code Object construction <?php include('Engine.php'); class Car { private $Engine; public function __construct($sEngine) { $this->Engine = Engine::getByType($sEngine); } }
  • 28. Testing untestable code Object construction - include_path <?php ini_set('include_path', '/custom/mocks/'.PATH_SEPARATOR. ini_get('include_path')); // Testcase include('car.php'); $oCar = new Car('Diesel'); echo $oCar->run();
  • 29. Testing untestable code Object construction – Stream Wrapper <?php class CustomWrapper { private $_handler; function stream_open($path, $mode, $options, &$opened_path) { stream_wrapper_restore('file'); // @TODO: modify $path before fopen $this->_handler = fopen($path, $mode); stream_wrapper_unregister('file'); stream_wrapper_register('file', 'CustomWrapper'); return true; } }
  • 30. Testing untestable code Object construction – Stream Wrapper stream_wrapper_unregister('file'); stream_wrapper_register('file', 'CustomWrapper');
  • 31. Testing untestable code Object construction – Stream Wrapper <?php class CustomWrapper { private $_handler ; function stream_read( $count ) { $content = fread($this->_handler, $count ); $content = str_replace ('Engine::getByType' , ' Abstract Engine::get' , $content ); return $content ; } }
  • 32. Testing untestable code Object construction – Namespaces <?php class Car { private $Engine; public function __construct($sEngine) { $this->Engine = CarEngine:: getByType($sEngine); } }
  • 33. Testing untestable code External resources
  • 34. Testing untestable code External resources Database Webservice Filesystem Mailserver
  • 35. Testing untestable code External resources – Mock database
  • 36. Testing untestable code External resources – Mock database Provide own implementation
  • 37. Testing untestable code External resources – Mock database ZF example: $db = new Custom_Db_Adapter(array()); Zend_Db_Table::setDefaultAdapter($db);
  • 38. Testing untestable code External resources – Mock database PHPUnit_Extensions_Database_TestCase
  • 39. Testing untestable code External resources – Mock database Proxy for your SQL Server
  • 40. Testing untestable code External resources – Mock webservice
  • 41. Testing untestable code External resources – Mock webservice Provide own implementation
  • 42. Testing untestable code External resources – Mock webservice Host redirect via /etc/hosts
  • 43. Testing untestable code External resources – Mock filesystem
  • 44. Testing untestable code External resources – Mock filesystem <?php // set up test environmemt vfsStream::setup('exampleDir'); // create directory in test enviroment mkdir(vfsStream::url('exampleDir').'/sample/'); // check if directory was created echo vfsStreamWrapper::getRoot()->hasChild('sample');
  • 45. Testing untestable code External resources – Mock Mailserver
  • 46. Testing untestable code External resources – Mock Mailserver Use fake mail server
  • 47. Testing untestable code External resources – Mock Mailserver $ cat /etc/php5/php.ini | grep sendmail_path sendmail_path=/usr/local/bin/logmail $ cat /usr/local/bin/logmail cat >> /tmp/logmail.log
  • 48. Testing untestable code Dealing with language issues
  • 49. Testing untestable code Dealing with language issues Testing your privates?
  • 50. Testing untestable code Dealing with language issues <?php class CustomWrapper { private $_handler; function stream_read($count) { $content = fread($this->_handler, $count); $content = str_replace( 'private function', 'public function', $content ); return $content; }
  • 51. Testing untestable code Dealing with language issues $myClass = new MyClass(); $reflectionClass = new ReflectionClass('MyClass'); $reflectionMethod = $reflectionClass-> getMethod('mydemo'); $reflectionMethod->setAccessible(true); $reflectionMethod->invoke($myClass);
  • 52. Testing untestable code Dealing with language issues Overwrite internal functions?
  • 53. Testing untestable code Dealing with language issues pecl install runkit-0.9
  • 54. Testing untestable code Dealing with language issues - Runkit <?php ini_set('runkit.internal_override', '1'); runkit_function_redefine('mail','','return true;'); ?>
  • 55. Testing untestable code Dealing with language issues pecl install funcall-0.3.0alpha
  • 56. Testing untestable code Dealing with language issues - Funcall <?php function my_func($arg1, $arg2) { return $arg1.$arg2; } function post_cb($args,$result,$process_time) { // return custom result based on $args } fc_add_post('my_func','post_cb'); var_dump(my_func('php', 'c'));
  • 58. Testing untestable code What else? Generative Programming
  • 59. Testing untestable code Generative Programming Configuration Configuration 1 ... n Implementation Implementation Generator Generator Product components components Product Generator Generator application application
  • 60. Testing untestable code Generative Programming Configuration Configuration Application Application Implementation Implementation Generator Generator components components Testcases Testcases Generator Generator application application
  • 61. Testing untestable code Generative Programming A frame is a data structure for representing knowledge.
  • 62. Testing untestable code A Frame instance <?php class Car { private $Engine; public function __construct($sEngine) { $this->Engine = <!{Factory}!>:: getByType($sEngine); } }
  • 63. Testing untestable code The Frame controller public class MyFrameController extends SimpleFrameController { public void execute(Frame frame, FeatureConfig config) { if(config.hasFeature("unittest")) { frame.setSlot("Factory", "FactoryMock"); } else { frame.setSlot("Factory", "EngineFactory"); } } }
  • 64. Testing untestable code Generated result - Testcase <?php class Car { private $Engine; public function __construct($sEngine) { $this->Engine = FactoryMock:: getByType($sEngine); } }
  • 65. Testing untestable code Generated result - Application <?php class Car { private $Engine; public function __construct($sEngine) { $this->Engine = EngineFactory:: getByType($sEngine); } }
  • 66. Testing untestable code What is possible?
  • 67. Testing untestable code What is possible? Show / hide parts of the code
  • 68. Testing untestable code What is possible? Change content of global vars!
  • 69. Testing untestable code What is possible? Define pre- or postfixes!
  • 70. Testing untestable code Is it worth it?
  • 71. Testing untestable code Conclusions Change your mindset to write testable code!
  • 72. Testing untestable code Conclusions PHP is a swiss-army knife. Use it that way!
  • 74. Testing untestable code Bildquellen http://www.flickr.com/photos/andresrueda/3452940751/ http://www.flickr.com/photos/andresrueda/3455410635/