SlideShare a Scribd company logo
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/

More Related Content

PDF
Testing untestable code - PHPBNL11
PDF
Testing untestable code - STPCon11
PDF
Testing untestable code - DPC10
PDF
Real World Dependency Injection - phpday
PDF
Real world dependency injection - DPC10
PDF
Testing untestable code - phpday
PDF
Testing untestable code - ConFoo13
PDF
Testing untestable code - oscon 2012
Testing untestable code - PHPBNL11
Testing untestable code - STPCon11
Testing untestable code - DPC10
Real World Dependency Injection - phpday
Real world dependency injection - DPC10
Testing untestable code - phpday
Testing untestable code - ConFoo13
Testing untestable code - oscon 2012

What's hot (20)

PDF
Testing untestable Code - PFCongres 2010
PDF
Real World Dependency Injection - PFCongres 2010
PPT
Invoke dynamics
PDF
Advanced java interview questions
PPTX
Playing with Java Classes and Bytecode
PDF
Living With Legacy Code
PDF
"Formal Verification in Java" by Shura Iline, Vladimir Ivanov @ JEEConf 2013,...
ODP
Mastering Mock Objects - Advanced Unit Testing for Java
PDF
Testing Legacy Rails Apps
PDF
Java Annotation Processing: A Beginner Walkthrough
PPT
Working Effectively With Legacy Code
PPT
Google mock for dummies
KEY
Developer testing 101: Become a Testing Fanatic
ODT
Testing in-python-and-pytest-framework
PDF
Working Effectively With Legacy Perl Code
PPTX
Java reflection
PDF
Spring IO 2015 Spock Workshop
PDF
Java object oriented programming - OOPS
PPTX
Refactoring
PPTX
TDD and the Legacy Code Black Hole
Testing untestable Code - PFCongres 2010
Real World Dependency Injection - PFCongres 2010
Invoke dynamics
Advanced java interview questions
Playing with Java Classes and Bytecode
Living With Legacy Code
"Formal Verification in Java" by Shura Iline, Vladimir Ivanov @ JEEConf 2013,...
Mastering Mock Objects - Advanced Unit Testing for Java
Testing Legacy Rails Apps
Java Annotation Processing: A Beginner Walkthrough
Working Effectively With Legacy Code
Google mock for dummies
Developer testing 101: Become a Testing Fanatic
Testing in-python-and-pytest-framework
Working Effectively With Legacy Perl Code
Java reflection
Spring IO 2015 Spock Workshop
Java object oriented programming - OOPS
Refactoring
TDD and the Legacy Code Black Hole
Ad

Viewers also liked (6)

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

Similar to Testing untestable code - phpconpl11 (20)

PDF
Testing untestable code - IPC12
PPTX
Test in action – week 1
PPTX
Regression Testing with Symfony
PDF
Unit and integration Testing
ZIP
Test
PDF
Your code are my tests
PPTX
Test in action week 2
PPT
Unit testing
PPTX
Test in action week 4
PDF
Bdd and-testing
PDF
Behaviour Driven Development and Thinking About Testing
 
PPTX
Testing 101
PPT
lec-11 Testing.ppt
PPTX
[DevDay2018] Unit testing in PHP and Laravel Framework - Unit testing in PHP ...
PDF
PHPUnit & Continuous Integration: An Introduction
PDF
Test driven development - Zombie proof your code
PDF
PHPunit and you
PDF
Fighting Fear-Driven-Development With PHPUnit
PPTX
Testing the untestable
DOCX
Faq
Testing untestable code - IPC12
Test in action – week 1
Regression Testing with Symfony
Unit and integration Testing
Test
Your code are my tests
Test in action week 2
Unit testing
Test in action week 4
Bdd and-testing
Behaviour Driven Development and Thinking About Testing
 
Testing 101
lec-11 Testing.ppt
[DevDay2018] Unit testing in PHP and Laravel Framework - Unit testing in PHP ...
PHPUnit & Continuous Integration: An Introduction
Test driven development - Zombie proof your code
PHPunit and you
Fighting Fear-Driven-Development With PHPUnit
Testing the untestable
Faq

More from Stephan Hochdörfer (20)

PDF
Offline. Na und? Strategien für offlinefähige Applikationen in HTML5 - Herbst...
PDF
Offline strategies for HTML5 web applications - frOSCon8
PDF
Offline Strategies for HTML5 Web Applications - oscon13
PDF
Real World Dependency Injection - oscon13
PDF
Dependency Injection in PHP - dwx13
PDF
Offline Strategien für HTML5 Web Applikationen - dwx13
PDF
Your Business. Your Language. Your Code - dpc13
PDF
Phing for power users - dpc_uncon13
PDF
Offline-Strategien für HTML5 Web Applikationen - wmka
PDF
Offline-Strategien für HTML5 Web Applikationen - bedcon13
PDF
Real World Dependency Injection - phpugffm13
PDF
A Phing fairy tale - ConFoo13
PDF
Offline strategies for HTML5 web applications - ConFoo13
PDF
Offline-Strategien für HTML5Web Applikationen - WMMRN12
PDF
Offline strategies for HTML5 web applications - IPC12
PDF
Große Systeme, lose Kopplung, Spaß bei der Arbeit! - WDC12
PDF
Offline strategies for HTML5 web applications - pfCongres2012
PDF
Wie Software-Generatoren die Welt verändern können - Herbstcampus12
PDF
Introducing a Software Generator Framework - JAZOON12
PDF
The state of DI - DPC12
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 - oscon13
Real World Dependency Injection - oscon13
Dependency Injection in PHP - dwx13
Offline Strategien für HTML5 Web Applikationen - dwx13
Your Business. Your Language. Your Code - dpc13
Phing for power users - dpc_uncon13
Offline-Strategien für HTML5 Web Applikationen - wmka
Offline-Strategien für HTML5 Web Applikationen - bedcon13
Real World Dependency Injection - phpugffm13
A Phing fairy tale - ConFoo13
Offline strategies for HTML5 web applications - ConFoo13
Offline-Strategien für HTML5Web Applikationen - WMMRN12
Offline strategies for HTML5 web applications - IPC12
Große Systeme, lose Kopplung, Spaß bei der Arbeit! - WDC12
Offline strategies for HTML5 web applications - pfCongres2012
Wie Software-Generatoren die Welt verändern können - Herbstcampus12
Introducing a Software Generator Framework - JAZOON12
The state of DI - DPC12

Recently uploaded (20)

PDF
Building Integrated photovoltaic BIPV_UPV.pdf
PDF
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
PPTX
Spectroscopy.pptx food analysis technology
PDF
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
PDF
Reach Out and Touch Someone: Haptics and Empathic Computing
PDF
Mobile App Security Testing_ A Comprehensive Guide.pdf
PDF
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
PDF
Advanced methodologies resolving dimensionality complications for autism neur...
DOCX
The AUB Centre for AI in Media Proposal.docx
PPTX
Programs and apps: productivity, graphics, security and other tools
PPTX
ACSFv1EN-58255 AWS Academy Cloud Security Foundations.pptx
PPTX
Cloud computing and distributed systems.
PDF
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
PPTX
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
PDF
Chapter 3 Spatial Domain Image Processing.pdf
PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
PDF
Approach and Philosophy of On baking technology
PDF
The Rise and Fall of 3GPP – Time for a Sabbatical?
PDF
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
Building Integrated photovoltaic BIPV_UPV.pdf
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
Spectroscopy.pptx food analysis technology
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
Reach Out and Touch Someone: Haptics and Empathic Computing
Mobile App Security Testing_ A Comprehensive Guide.pdf
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
Advanced methodologies resolving dimensionality complications for autism neur...
The AUB Centre for AI in Media Proposal.docx
Programs and apps: productivity, graphics, security and other tools
ACSFv1EN-58255 AWS Academy Cloud Security Foundations.pptx
Cloud computing and distributed systems.
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
Chapter 3 Spatial Domain Image Processing.pdf
Diabetes mellitus diagnosis method based random forest with bat algorithm
Approach and Philosophy of On baking technology
The Rise and Fall of 3GPP – Time for a Sabbatical?
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...

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/