SlideShare uma empresa Scribd logo
1 de 74
Baixar para ler offline
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/

Mais conteúdo relacionado

Mais procurados

Testing untestable Code - PFCongres 2010
Testing untestable Code - PFCongres 2010Testing untestable Code - PFCongres 2010
Testing untestable Code - PFCongres 2010Stephan Hochdörfer
 
Real World Dependency Injection - PFCongres 2010
Real World Dependency Injection - PFCongres 2010Real World Dependency Injection - PFCongres 2010
Real World Dependency Injection - PFCongres 2010Stephan Hochdörfer
 
Advanced java interview questions
Advanced java interview questionsAdvanced java interview questions
Advanced java interview questionsrithustutorials
 
Playing with Java Classes and Bytecode
Playing with Java Classes and BytecodePlaying with Java Classes and Bytecode
Playing with Java Classes and BytecodeYoav Avrahami
 
Living With Legacy Code
Living With Legacy CodeLiving With Legacy Code
Living With Legacy CodeRowan Merewood
 
"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
 
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 JavaDenilson Nastacio
 
Testing Legacy Rails Apps
Testing Legacy Rails AppsTesting Legacy Rails Apps
Testing Legacy Rails AppsRabble .
 
Java Annotation Processing: A Beginner Walkthrough
Java Annotation Processing: A Beginner WalkthroughJava Annotation Processing: A Beginner Walkthrough
Java Annotation Processing: A Beginner WalkthroughMahfuz Islam Bhuiyan
 
Working Effectively With Legacy Code
Working Effectively With Legacy CodeWorking Effectively With Legacy Code
Working Effectively With Legacy CodeNaresh Jain
 
Google mock for dummies
Google mock for dummiesGoogle mock for dummies
Google mock for dummiesHarry Potter
 
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 FanaticLB Denker
 
Testing in-python-and-pytest-framework
Testing in-python-and-pytest-frameworkTesting in-python-and-pytest-framework
Testing in-python-and-pytest-frameworkArulalan T
 
Working Effectively With Legacy Perl Code
Working Effectively With Legacy Perl CodeWorking Effectively With Legacy Perl Code
Working Effectively With Legacy Perl Codeerikmsp
 
Java object oriented programming - OOPS
Java object oriented programming - OOPSJava object oriented programming - OOPS
Java object oriented programming - OOPSrithustutorials
 
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 HoleNoam Kfir
 

Mais procurados (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
 

Destaque

Testing untestable code - PHPUGFFM 01/11
Testing untestable code - PHPUGFFM 01/11Testing untestable code - PHPUGFFM 01/11
Testing untestable code - PHPUGFFM 01/11Stephan Hochdörfer
 
Testing untestable code - Herbstcampus12
Testing untestable code - Herbstcampus12Testing untestable code - Herbstcampus12
Testing untestable code - Herbstcampus12Stephan Hochdörfer
 
Simplify your external dependency management - DPC11
Simplify your external dependency management - DPC11Simplify your external dependency management - DPC11
Simplify your external dependency management - DPC11Stephan Hochdörfer
 
Facebook für PHP Entwickler - phpugffm
Facebook für PHP Entwickler - phpugffmFacebook für PHP Entwickler - phpugffm
Facebook für PHP Entwickler - phpugffmStephan 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 - ipc13Stephan Hochdörfer
 
Phing for power users - frOSCon8
Phing for power users - frOSCon8Phing for power users - frOSCon8
Phing for power users - frOSCon8Stephan Hochdörfer
 

Destaque (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
 

Semelhante a Testing untestable code - phpconpl11

Automated infrastructure testing - by Ranjib Dey
Automated infrastructure testing - by Ranjib DeyAutomated infrastructure testing - by Ranjib Dey
Automated infrastructure testing - by Ranjib Deybhumika2108
 
Automated Infrastructure Testing
Automated Infrastructure TestingAutomated Infrastructure Testing
Automated Infrastructure TestingRanjib Dey
 
Unit tests & TDD
Unit tests & TDDUnit tests & TDD
Unit tests & TDDDror Helper
 
Automated Infrastructure Testing - Ranjib Dey
Automated Infrastructure Testing - Ranjib DeyAutomated Infrastructure Testing - Ranjib Dey
Automated Infrastructure Testing - Ranjib DeyThoughtworks
 
Extreme
ExtremeExtreme
ExtremeESUG
 
Unit Testing Android Applications
Unit Testing Android ApplicationsUnit Testing Android Applications
Unit Testing Android ApplicationsRody Middelkoop
 
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...GlobalLogic Ukraine
 
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 jasmineGil Fink
 
Bypass Security Checking with Frida
Bypass Security Checking with FridaBypass Security Checking with Frida
Bypass Security Checking with FridaSatria Ady Pradana
 
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)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 2014DA-14
 
TDD and mock objects
TDD and mock objectsTDD and mock objects
TDD and mock objectsSteve Zhang
 
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 WorkshopWolfram Arnold
 

Semelhante a 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
 

Mais de 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 - frOSCon8Stephan 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 - oscon13Stephan Hochdörfer
 
Real World Dependency Injection - oscon13
Real World Dependency Injection - oscon13Real World Dependency Injection - oscon13
Real World Dependency Injection - oscon13Stephan Hochdörfer
 
Dependency Injection in PHP - dwx13
Dependency Injection in PHP - dwx13Dependency Injection in PHP - dwx13
Dependency Injection in PHP - dwx13Stephan 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 - dpc13Stephan Hochdörfer
 
Phing for power users - dpc_uncon13
Phing for power users - dpc_uncon13Phing for power users - dpc_uncon13
Phing for power users - dpc_uncon13Stephan 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 - wmkaStephan 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 - bedcon13Stephan Hochdörfer
 
Real World Dependency Injection - phpugffm13
Real World Dependency Injection - phpugffm13Real World Dependency Injection - phpugffm13
Real World Dependency Injection - phpugffm13Stephan 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 - ConFoo13Stephan 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 - WMMRN12Stephan 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 - IPC12Stephan 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! - WDC12Stephan 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 - pfCongres2012Stephan 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 - Herbstcampus12Stephan Hochdörfer
 
Introducing a Software Generator Framework - JAZOON12
Introducing a Software Generator Framework - JAZOON12Introducing a Software Generator Framework - JAZOON12
Introducing a Software Generator Framework - JAZOON12Stephan Hochdörfer
 

Mais de 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
 

Último

A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?Igalia
 
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
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
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
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
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
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
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
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?Antenna Manufacturer Coco
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Igalia
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 

Último (20)

A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
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
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
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
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
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...
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
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
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 

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/