SlideShare a Scribd company logo
Testing untestable code
Stephan Hochdörfer, bitExpert AG
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 - oscon 2012
Testing untestable code - oscon 2012
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 - oscon 2012
Testing untestable code - oscon 2012
Testing untestable code - oscon 2012
Testing untestable code - oscon 2012
Testing untestable code - oscon 2012
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 - oscon 2012
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');
 echo $oCar­>run();
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',
        'AbstractEngine::get', $content);
       return $content;
    }
 }
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

 Dealing with language issues




               funcall for methods?
Testing untestable code

 Dealing with language issues




 git clone https://github/juliens/AOP
Testing untestable code

 Dealing with language issues - AOP
 <?php

 aop_add_after('Car::drive*', 
 'adviceForDrive');
Testing untestable code

 Dealing with language issues - AOP
 <?php

 $advice = function(AopTriggeredJoinpoint
 $jp) {
   $returnValue = 
      $jp­>getReturnedValue();

   // modify the return value
   $returnValue = 1234;

   $jp­>setReturnedValue($returnValue);
 };

 aop_add_after('Car­>drive()', $advice);
Testing untestable code - oscon 2012
Testing untestable code

 What else?




           Generative Programming
Testing untestable code

 Generative Programming

                          Configuration
                           Configuration
                             (DSL)
                              (DSL)



                                           1..n
   Implementation-
    Implementation-
     components
                          Generator
                          Generator          Product
      components                              Product
Testing untestable code

 Generative Programming

                          Configuration
                           Configuration
                             (DSL)
                              (DSL)
                                           Customer 22
                                            Customer



   Implementation-
    Implementation-
     components
                          Generator
                          Generator        Customer 11
      components                            Customer
Testing untestable code

 Generative Programming

                          Configuration
                           Configuration
                             (DSL)
                              (DSL)
                                              Test
                                               Test
                                           Enviroment
                                            Enviroment



   Implementation-
    Implementation-
     components
                          Generator
                          Generator          Prod.
                                              Prod.
      components                           Enviroment
                                            Enviroment
Testing untestable code

 Generative Programming




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

 Frame
 <?php
 class Car {
    private $Engine;

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

 }
Testing untestable code

 ContentProvider for the Frame
 public class MyContentProvider extends
     AbstractContentProvider {
     public SlotConfiguration computeSlots(
         FeatureConfiguration config) {
         SlotConfiguration sl = new SlotConfiguration();

         if(config.hasFeature("unittest")) {
             sl.put("Factory", "FactoryMock");
         } else {
             sl.put("Factory", "EngineFactory");
         }
         return sl;
     }
 }
Testing untestable code

 Generated result – Test Enviroment
 <?php
 class Car {
    private $Engine;

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

 }
Testing untestable code

 Generated result – Prod. Enviroment
 <?php
 class Car {
    private $Engine;

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

 }
Testing untestable code

 Curious for more?




                     http://replicatorframework.org
Thank you!
Please rate: http://bit.ly/ML0alS

More Related Content

PDF
Real World Dependency Injection - PFCongres 2010
PDF
Real World Dependency Injection SE - phpugrhh
PDF
Real world dependency injection - DPC10
PDF
Testing untestable code - DPC10
PDF
Testing untestable code - phpconpl11
PDF
Dependency Injection in PHP - dwx13
PDF
Real World Dependency Injection - phpugffm13
PDF
Real World Dependency Injection - IPC11 Spring Edition
Real World Dependency Injection - PFCongres 2010
Real World Dependency Injection SE - phpugrhh
Real world dependency injection - DPC10
Testing untestable code - DPC10
Testing untestable code - phpconpl11
Dependency Injection in PHP - dwx13
Real World Dependency Injection - phpugffm13
Real World Dependency Injection - IPC11 Spring Edition

What's hot (20)

PDF
Testing untestable Code - PFCongres 2010
PDF
Top 100 Java Interview Questions with Detailed Answers
PDF
Testing untestable code - STPCon11
KEY
IoC with PHP
PDF
Create Your Own Framework by Fabien Potencier
ODP
Dependency Injection, Zend Framework and Symfony Container
PDF
Advanced java interview questions
PPS
Authentication with zend framework
PDF
JDT Fundamentals 2010
PDF
Using Contexts & Dependency Injection in the Java EE 6 Platform
PPT
Contexts and Dependency Injection for the JavaEE platform
PDF
Java j2ee interview_questions
PPT
Spring frame work
PDF
iOS API Design
ODP
Implementing security routines with zf2
PDF
Java Programming | Java Tutorial For Beginners | Java Training | Edureka
PDF
Java Training | Java Tutorial for Beginners | Java Programming | Java Certifi...
PDF
Core java interview questions
PPTX
Dev labs alliance top 20 basic java interview question for sdet
PDF
Instant ACLs with Zend Framework 2
Testing untestable Code - PFCongres 2010
Top 100 Java Interview Questions with Detailed Answers
Testing untestable code - STPCon11
IoC with PHP
Create Your Own Framework by Fabien Potencier
Dependency Injection, Zend Framework and Symfony Container
Advanced java interview questions
Authentication with zend framework
JDT Fundamentals 2010
Using Contexts & Dependency Injection in the Java EE 6 Platform
Contexts and Dependency Injection for the JavaEE platform
Java j2ee interview_questions
Spring frame work
iOS API Design
Implementing security routines with zf2
Java Programming | Java Tutorial For Beginners | Java Training | Edureka
Java Training | Java Tutorial for Beginners | Java Programming | Java Certifi...
Core java interview questions
Dev labs alliance top 20 basic java interview question for sdet
Instant ACLs with Zend Framework 2
Ad

Viewers also liked (6)

PDF
Facebook Apps: Ein Entwicklungsleitfaden - WMMRN
PDF
Offline strategies for HTML5 web applications - IPC12
PDF
Phing for power users - dpc_uncon13
PDF
Offline-Strategien für HTML5Web Applikationen - WMMRN12
PDF
The state of DI in PHP - phpbnl12
PDF
Große Systeme, lose Kopplung, Spaß bei der Arbeit! - WDC12
Facebook Apps: Ein Entwicklungsleitfaden - WMMRN
Offline strategies for HTML5 web applications - IPC12
Phing for power users - dpc_uncon13
Offline-Strategien für HTML5Web Applikationen - WMMRN12
The state of DI in PHP - phpbnl12
Große Systeme, lose Kopplung, Spaß bei der Arbeit! - WDC12
Ad

Similar to Testing untestable code - oscon 2012 (20)

PDF
Testing untestable code - phpday
PDF
Testing untestable code - ConFoo13
PDF
Testing untestable code - IPC12
PPTX
Automated infrastructure testing - by Ranjib Dey
PPTX
Automated Infrastructure Testing
PPTX
Automated Infrastructure Testing - Ranjib Dey
PPTX
Coding Naked
ZIP
Test
PPTX
Unit test
PPTX
Unit tests & TDD
PPTX
Static Code Analysis PHP[tek] 2023
PDF
Extreme
PPTX
GlobalLogic Test Automation Online TechTalk “Test Driven Development as a Per...
ZIP
Automated Frontend Testing
PPTX
Understanding JavaScript Testing
PPTX
Test driven development for infrastructure as-a-code, the future trend_Gianfr...
PPTX
Coding Naked 2023
PDF
Config Management Camp 2017 - If it moves, give it a pipeline
PDF
Test Automation and Keyword-driven testing af Brian Nielsen, CISS/AAU
PDF
Test driven development
Testing untestable code - phpday
Testing untestable code - ConFoo13
Testing untestable code - IPC12
Automated infrastructure testing - by Ranjib Dey
Automated Infrastructure Testing
Automated Infrastructure Testing - Ranjib Dey
Coding Naked
Test
Unit test
Unit tests & TDD
Static Code Analysis PHP[tek] 2023
Extreme
GlobalLogic Test Automation Online TechTalk “Test Driven Development as a Per...
Automated Frontend Testing
Understanding JavaScript Testing
Test driven development for infrastructure as-a-code, the future trend_Gianfr...
Coding Naked 2023
Config Management Camp 2017 - If it moves, give it a pipeline
Test Automation and Keyword-driven testing af Brian Nielsen, CISS/AAU
Test driven development

More from Stephan Hochdörfer (20)

PDF
Offline. Na und? Strategien für offlinefähige Applikationen in HTML5 - Herbst...
PDF
Phing for power users - frOSCon8
PDF
Offline strategies for HTML5 web applications - frOSCon8
PDF
Offline Strategies for HTML5 Web Applications - oscon13
PDF
Real World Dependency Injection - oscon13
PDF
Offline Strategien für HTML5 Web Applikationen - dwx13
PDF
Your Business. Your Language. Your Code - dpc13
PDF
Offline Strategies for HTML5 Web Applications - ipc13
PDF
Offline-Strategien für HTML5 Web Applikationen - wmka
PDF
Offline-Strategien für HTML5 Web Applikationen - bedcon13
PDF
A Phing fairy tale - ConFoo13
PDF
Offline strategies for HTML5 web applications - ConFoo13
PDF
Offline strategies for HTML5 web applications - pfCongres2012
PDF
Wie Software-Generatoren die Welt verändern können - Herbstcampus12
PDF
Testing untestable code - Herbstcampus12
PDF
Introducing a Software Generator Framework - JAZOON12
PDF
The state of DI - DPC12
PDF
Separation of concerns - DPC12
PDF
Managing variability in software applications - scandev12
PDF
Facebook für PHP Entwickler - phpugffm
Offline. Na und? Strategien für offlinefähige Applikationen in HTML5 - Herbst...
Phing for power users - frOSCon8
Offline strategies for HTML5 web applications - frOSCon8
Offline Strategies for HTML5 Web Applications - oscon13
Real World Dependency Injection - oscon13
Offline Strategien für HTML5 Web Applikationen - dwx13
Your Business. Your Language. Your Code - dpc13
Offline Strategies for HTML5 Web Applications - ipc13
Offline-Strategien für HTML5 Web Applikationen - wmka
Offline-Strategien für HTML5 Web Applikationen - bedcon13
A Phing fairy tale - ConFoo13
Offline strategies for HTML5 web applications - ConFoo13
Offline strategies for HTML5 web applications - pfCongres2012
Wie Software-Generatoren die Welt verändern können - Herbstcampus12
Testing untestable code - Herbstcampus12
Introducing a Software Generator Framework - JAZOON12
The state of DI - DPC12
Separation of concerns - DPC12
Managing variability in software applications - scandev12
Facebook für PHP Entwickler - phpugffm

Recently uploaded (20)

PDF
Review of recent advances in non-invasive hemoglobin estimation
PDF
Electronic commerce courselecture one. Pdf
PPTX
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
PDF
Machine learning based COVID-19 study performance prediction
PPT
Teaching material agriculture food technology
PPTX
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
PPTX
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
PDF
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
PDF
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
PDF
MIND Revenue Release Quarter 2 2025 Press Release
PDF
Encapsulation theory and applications.pdf
PDF
KodekX | Application Modernization Development
PDF
Unlocking AI with Model Context Protocol (MCP)
PDF
cuic standard and advanced reporting.pdf
PPTX
Programs and apps: productivity, graphics, security and other tools
PDF
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
PPT
“AI and Expert System Decision Support & Business Intelligence Systems”
PDF
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
PDF
Chapter 3 Spatial Domain Image Processing.pdf
PDF
Approach and Philosophy of On baking technology
Review of recent advances in non-invasive hemoglobin estimation
Electronic commerce courselecture one. Pdf
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
Machine learning based COVID-19 study performance prediction
Teaching material agriculture food technology
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
MIND Revenue Release Quarter 2 2025 Press Release
Encapsulation theory and applications.pdf
KodekX | Application Modernization Development
Unlocking AI with Model Context Protocol (MCP)
cuic standard and advanced reporting.pdf
Programs and apps: productivity, graphics, security and other tools
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
“AI and Expert System Decision Support & Business Intelligence Systems”
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
Chapter 3 Spatial Domain Image Processing.pdf
Approach and Philosophy of On baking technology

Testing untestable code - oscon 2012

  • 1. Testing untestable code Stephan Hochdörfer, bitExpert AG
  • 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!
  • 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“?
  • 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
  • 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'); echo $oCar­>run();
  • 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',        'AbstractEngine::get', $content); return $content; } }
  • 32. Testing untestable code External resources
  • 33. Testing untestable code External resources Database Webservice Filesystem Mailserver
  • 34. Testing untestable code External resources – Mock database
  • 35. Testing untestable code External resources – Mock database Provide own implementation
  • 36. Testing untestable code External resources – Mock database ZF example: $db = new Custom_Db_Adapter(array()); Zend_Db_Table::setDefaultAdapter($db);
  • 37. Testing untestable code External resources – Mock database PHPUnit_Extensions_Database_TestCase
  • 38. Testing untestable code External resources – Mock database Proxy for your SQL Server
  • 39. Testing untestable code External resources – Mock webservice
  • 40. Testing untestable code External resources – Mock webservice Provide own implementation
  • 41. Testing untestable code External resources – Mock webservice Host redirect via /etc/hosts
  • 42. Testing untestable code External resources – Mock filesystem
  • 43. 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');
  • 44. Testing untestable code External resources – Mock Mailserver
  • 45. Testing untestable code External resources – Mock Mailserver Use fake mail server
  • 46. 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
  • 47. Testing untestable code Dealing with language issues
  • 48. Testing untestable code Dealing with language issues Testing your privates?
  • 49. 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; } }
  • 50. Testing untestable code Dealing with language issues $myClass = new MyClass(); $reflectionClass  = new ReflectionClass('MyClass'); $reflectionMethod = $reflectionClass­> getMethod('mydemo'); $reflectionMethod­>setAccessible(true); $reflectionMethod­>invoke($myClass);
  • 51. Testing untestable code Dealing with language issues Overwrite internal functions?
  • 52. Testing untestable code Dealing with language issues pecl install runkit-0.9
  • 53. Testing untestable code Dealing with language issues - Runkit <?php ini_set('runkit.internal_override', '1'); runkit_function_redefine('mail','','return  true;'); ?>
  • 54. Testing untestable code Dealing with language issues pecl install funcall-0.3.0alpha
  • 55. 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'));
  • 56. Testing untestable code Dealing with language issues funcall for methods?
  • 57. Testing untestable code Dealing with language issues git clone https://github/juliens/AOP
  • 58. Testing untestable code Dealing with language issues - AOP <?php aop_add_after('Car::drive*',  'adviceForDrive');
  • 59. Testing untestable code Dealing with language issues - AOP <?php $advice = function(AopTriggeredJoinpoint $jp) {   $returnValue =       $jp­>getReturnedValue();   // modify the return value   $returnValue = 1234;   $jp­>setReturnedValue($returnValue); }; aop_add_after('Car­>drive()', $advice);
  • 61. Testing untestable code What else? Generative Programming
  • 62. Testing untestable code Generative Programming Configuration Configuration (DSL) (DSL) 1..n Implementation- Implementation- components Generator Generator Product components Product
  • 63. Testing untestable code Generative Programming Configuration Configuration (DSL) (DSL) Customer 22 Customer Implementation- Implementation- components Generator Generator Customer 11 components Customer
  • 64. Testing untestable code Generative Programming Configuration Configuration (DSL) (DSL) Test Test Enviroment Enviroment Implementation- Implementation- components Generator Generator Prod. Prod. components Enviroment Enviroment
  • 65. Testing untestable code Generative Programming A frame is a data structure for representing knowledge.
  • 66. Testing untestable code Frame <?php class Car { private $Engine; public function __construct($sEngine) { $this­>Engine = <!{Factory}!>:: getByType($sEngine); } }
  • 67. Testing untestable code ContentProvider for the Frame public class MyContentProvider extends     AbstractContentProvider {     public SlotConfiguration computeSlots(         FeatureConfiguration config) {         SlotConfiguration sl = new SlotConfiguration();         if(config.hasFeature("unittest")) {             sl.put("Factory", "FactoryMock");         } else {             sl.put("Factory", "EngineFactory");         }         return sl;     } }
  • 68. Testing untestable code Generated result – Test Enviroment <?php class Car { private $Engine; public function __construct($sEngine) { $this­>Engine = FactoryMock:: getByType($sEngine); } }
  • 69. Testing untestable code Generated result – Prod. Enviroment <?php class Car { private $Engine; public function __construct($sEngine) { $this­>Engine = EngineFactory:: getByType($sEngine); } }
  • 70. Testing untestable code Curious for more? http://replicatorframework.org