SlideShare a Scribd company logo
Testing untestable Code
   Stephan Hochdörfer, bitExpert AG




 "Quality is a function of thought and reflection -
 precise thought and reflection. That’s the magic."
                 Michael Feathers
Agenda
1.   About me

2.   Theory

3.   How to test untestable code

4.   Generating testable code

5.   Conclusions

6.   Questions
About me
 Stephan Hochdörfer, bitExpert AG

 Department Manager Research Labs

 enjoying PHP since 1999

 S.Hochdoerfer@bitExpert.de

 @shochdoerfer
No excuse for bad code!
Warning! Use at own risk...
Theory




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



 What is „untestable code“?
Theory



 What is „untestable code“?
Theory



 What is „untestable code“?
Theory




          "...our test strategy requires us to have more control or
         visibility of the internal behavior of the system under test."
               Gerard Meszaros, xUnit Test Patterns: Refactoring Test Code
Theory




                               Required
                                class
                    Class to
         Unittest
                      Test
                               Required
                                class
Theory




                                          Database

                               Required
                                class
                                           External
                    Class to
         Unittest                          resource
                      test
                               Required
                                class




                    Required   Required
                                           Webservice
                     class      class
Theory




                                          Database

                               Required
                                class
                                           External
                    Class to
         Unittest                          resource
                      test
                               Required
                                class




                    Required   Required
                                           Webservice
                     class      class
Theory



 How to achieve „testable“ code?
Theory



 How to achieve „testable“ code?




                Refactoring
Theory




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



 Let the work begin...
Testing „untestable“ PHP Code



 For your safty!




          Do not change existing code!
Testing „untestable“ PHP Code | __autoload




<?php
class Car {
    private $Engine;

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

}
Testing „untestable“ PHP Code | __autoload




<?php
class Car {
    private $Engine;

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

}




How to inject a dependency?
 Use __autoload
Testing „untestable“ PHP Code | __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“ PHP Code | include_path




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

class Car {
    private $Engine;

     public function __construct($sEngine) {
         $this->Engine = Engine::getByType($sEngine);
     }
}
Testing „untestable“ PHP Code | include_path




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

class Car {
    private $Engine;

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




How to inject a dependency?
 Manipulate include_path setting
Testing „untestable“ PHP Code | 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“ PHP Code | include_path alternative

<?php
class CustomFileStreamWrapper {
  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', 'CustomFileStreamWrapper');
      return true;
    }

    function stream_read($count) {}

    function stream_write($data) {}

    function stream_tell() {}

    function stream_eof() {}

    function stream_seek($offset, $whence) {}
}

stream_wrapper_unregister('file');
stream_wrapper_register('file', 'CustomFileStreamWrapper');



Source: Alex Netkachov, http://www.alexatnet.com/node/203
Testing „untestable“ PHP Code | include_path alternative

<?php
class CustomFileStreamWrapper {
      private $_handler;

       function stream_open($path, $mode, $options, &$opened_path) {
            stream_wrapper_restore('file');
            $this->_handler = fopen($path, $mode);
            stream_wrapper_unregister('file');
            stream_wrapper_register('file', 'CustomFileStreamWrapper');
            return true;
       }

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

stream_wrapper_unregister('file');
stream_wrapper_register('file', 'CustomFileStreamWrapper');

include('engine.php');
?>
Testing „untestable“ PHP Code | Namespaces




<?php
class Car {
    private $Engine;

     public function __construct($sEngine) {
         $this->Engine = CarEngine::getByType($sEngine);
     }
}
Testing „untestable“ PHP Code | Namespaces




<?php
class Car {
    private $Engine;

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




How to inject a dependency?
 Use __autoload or manipulate the include_path
Testing „untestable“ PHP Code | vfsStream




<?php
class Car {
    private $Engine;

     public function __construct($sEngine, $CacheDir) {
         $this->Engine = CarEngine::getByType($sEngine);
         mkdir($CacheDir.'/cache/', 0700, true);
     }
}
Testing „untestable“ PHP Code | vfsStream




<?php
class Car {
    private $Engine;

     public function __construct($sEngine, $CacheDir) {
         $this->Engine = CarEngine::getByType($sEngine);
         mkdir($CacheDir.'/cache/', 0700, true);
     }
}




How mock a filesystem?
 Use vfsStream - http://code.google.com/p/bovigo/
Testing „untestable“ PHP Code | vfsStream




<?php

// setup vfsStream
vfsStreamWrapper::register();
vfsStreamWrapper::setRoot(new vfsStreamDirectory('app'));

$oCar = new Car('Diesel', vfsStream::url('app'));

echo vfsStreamWrapper::getRoot()->hasChild('cache');
Testing „untestable“ PHP Code




       „I have no idea how to unit-test procedural code. Unit-testing
          assumes that I can instantiate a piece of my application in
                                  isolation.“
                                 Miško Hevery
Testing „untestable“ PHP Code | Test functions




<?php
function startsWith($sString, $psPre) {
    return $psPre == substr($sString, 0, strlen($psPre));
}

function contains($sString, $sSearch) {
    return false !== strpos($sString, $sSearch);
}
Testing „untestable“ PHP Code | Test functions




<?php
function startsWith($sString, $psPre) {
    return $psPre == substr($sString, 0, strlen($psPre));
}

function contains($sString, $sSearch) {
    return false !== strpos($sString, $sSearch);
}




How to test
 PHPUnit can call functions
 PHPUnit can save/restore globale state
Testing „untestable“ PHP Code | overwrite internal functions




<?php
function buyCar(Car $oCar) {
    global $oDB;

     mysql_query("INSERT INTO...", $oDB);

     mail('order@domain.org', 'New sale', '....');
}
Testing „untestable“ PHP Code | overwrite internal functions




<?php
function buyCar(Car $oCar) {
    global $oDB;

     mysql_query("INSERT INTO...", $oDB);

     mail('order@domain.org', 'New sale', '....');
}




How to test
 Do not load mysql extension. Provide own implementation
 Unfortunatley mail() is part of the PHP core
Testing „untestable“ PHP Code | overwrite internal functions




<?php
function buyCar(Car $oCar) {
    global $oDB;

     mysql_query("INSERT INTO...", $oDB);

     mail('order@domain.org', 'New sale', '....');
}




How to test
 Use classkit extension to overwrite internal functions
Testing „untestable“ PHP Code | overwrite internal functions




<?php

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

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

?>
Testing „untestable“ PHP Code
Generating testable code



 Generative Programming
Generating testable code



 Generative Programming

                             Configuration




                                                         1 ... n
            Implementation
                                             Generator    Product
             components




                               Generator
                               application
Generating testable code



 Generative Programming

                             Configuration


                                                         Application



            Implementation
                                             Generator
             components



                                                         Testcases
                               Generator
                               application
Generating testable code



 Course of action
 Extraction
  „Mask“ parts of the code


 Customizing
  Change content of global vars
  Pre/Postfixes for own functions, methods, classes


 Recombine
  Re-order parts of the code
Generating testable code




FileFrm FILEIndex_php5 {
  private String Prefix   = "test_";
  private String MailSlot = "mail('order@domain.org', 'New sale', '....');";

   public FILEIndex_php5() {
     setFilename("index.php5");
     setRelativePath("/");
   }

  private void assign() {
BEGINCONTENT()
<?php
function buyCar(Car $oCar) {
global $oDB;

<!{Prefix}!>mysql_query(„INSERT INTO...“, $oDB);
<!{MailSlot}!>
}

?>
ENDCONTENT()
  }
}
Generating testable code




1. Example
Prefix: test_
<?php
function buyCar(Car $oCar) {
  global $oDB;

    test_mysql_query("INSERT INTO...", $oDB);
}
Generating testable code




1. Example
Prefix: test_
<?php
function buyCar(Car $oCar) {
  global $oDB;

     test_mysql_query("INSERT INTO...", $oDB);
}


2. Example
MailSlot: mail('order@domain.org', 'New sale', '....');
<?php
function buyCar(Car $oCar) {
  global $oDB;

     mysql_query("INSERT INTO...", $oDB);
     mail('order@domain.org', 'New sale', '....');
}

?>
Conclusion



 How much effort to take?
Conclusion



 Conclusion

  Change mindset to write testable code
        
          Dependency Injection

  Look for other options to raise the bar
         
           Work around limitations of PHP
         
           PHP is flexible, use it that way
http://joind.in/1545

More Related Content

PDF
Real world dependency injection - DPC10
PDF
Testing untestable code - PHPBNL11
PDF
Testing untestable Code - PFCongres 2010
PDF
Testing untestable code - phpconpl11
PDF
Real World Dependency Injection - phpday
PDF
Testing untestable code - phpday
PDF
Testing untestable code - oscon 2012
PDF
Testing untestable code - STPCon11
Real world dependency injection - DPC10
Testing untestable code - PHPBNL11
Testing untestable Code - PFCongres 2010
Testing untestable code - phpconpl11
Real World Dependency Injection - phpday
Testing untestable code - phpday
Testing untestable code - oscon 2012
Testing untestable code - STPCon11

What's hot (20)

PDF
Real World Dependency Injection - PFCongres 2010
PDF
Real World Dependency Injection - IPC11 Spring Edition
PDF
Real World Dependency Injection SE - phpugrhh
PDF
QA Lab: тестирование ПО. Станислав Шмидт: "Self-testing REST APIs with API Fi...
PDF
QA Lab: тестирование ПО. Яков Крамаренко: "KISS Automation"
PDF
Testing untestable code - ConFoo13
KEY
Developer testing 101: Become a Testing Fanatic
PPTX
PHP 7 Crash Course
PDF
Invoke dynamite in Java EE with invoke dynamic
PPT
Invoke dynamics
PDF
Workshop quality assurance for php projects - phpdublin
KEY
Working Effectively With Legacy Code
PDF
Advanced java interview questions
PDF
Living With Legacy Code
PPT
Spring frame work
PPTX
4.Spring IoC&DI(Spring Ioc실습_어노테이션 기반)
PDF
Serial Killer - Silently Pwning your Java Endpoints // OWASP BeNeLux Day 2016
PPTX
Laravel Unit Testing
PPTX
PDF
Javascript Best Practices
Real World Dependency Injection - PFCongres 2010
Real World Dependency Injection - IPC11 Spring Edition
Real World Dependency Injection SE - phpugrhh
QA Lab: тестирование ПО. Станислав Шмидт: "Self-testing REST APIs with API Fi...
QA Lab: тестирование ПО. Яков Крамаренко: "KISS Automation"
Testing untestable code - ConFoo13
Developer testing 101: Become a Testing Fanatic
PHP 7 Crash Course
Invoke dynamite in Java EE with invoke dynamic
Invoke dynamics
Workshop quality assurance for php projects - phpdublin
Working Effectively With Legacy Code
Advanced java interview questions
Living With Legacy Code
Spring frame work
4.Spring IoC&DI(Spring Ioc실습_어노테이션 기반)
Serial Killer - Silently Pwning your Java Endpoints // OWASP BeNeLux Day 2016
Laravel Unit Testing
Javascript Best Practices
Ad

Similar to Testing untestable code - DPC10 (20)

PDF
Leveling Up With Unit Testing - LonghornPHP 2022
PDF
Leveling Up With Unit Testing - php[tek] 2023
PDF
Unit Testing from Setup to Deployment
ZIP
Test
PPT
Test Driven Development with PHPUnit
PDF
Testing untestable code - IPC12
PDF
Better Testing With PHP Unit
PPTX
Test in action week 2
PDF
2010 07-28-testing-zf-apps
PPTX
Junit_.pptx
KEY
Workshop quality assurance for php projects tek12
PDF
Quality Assurance for PHP projects - ZendCon 2012
PPTX
Test in action – week 1
PPT
Automated Unit Testing
PDF
Working Effectively With Legacy Perl Code
ODP
Good Practices On Test Automation
PDF
What's new in PHP 8.0?
PDF
Nikita Popov "What’s new in PHP 8.0?"
PDF
EPHPC Webinar Slides: Unit Testing by Arthur Purnama
PPTX
More on Fitnesse and Continuous Integration (Silicon Valley code camp 2012)
Leveling Up With Unit Testing - LonghornPHP 2022
Leveling Up With Unit Testing - php[tek] 2023
Unit Testing from Setup to Deployment
Test
Test Driven Development with PHPUnit
Testing untestable code - IPC12
Better Testing With PHP Unit
Test in action week 2
2010 07-28-testing-zf-apps
Junit_.pptx
Workshop quality assurance for php projects tek12
Quality Assurance for PHP projects - ZendCon 2012
Test in action – week 1
Automated Unit Testing
Working Effectively With Legacy Perl Code
Good Practices On Test Automation
What's new in PHP 8.0?
Nikita Popov "What’s new in PHP 8.0?"
EPHPC Webinar Slides: Unit Testing by Arthur Purnama
More on Fitnesse and Continuous Integration (Silicon Valley code camp 2012)
Ad

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
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 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
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
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
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 Strategies for HTML5 Web Applications - ipc13
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

Recently uploaded (20)

PDF
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
PPTX
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
PDF
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
PDF
Dropbox Q2 2025 Financial Results & Investor Presentation
PDF
Spectral efficient network and resource selection model in 5G networks
PDF
Chapter 3 Spatial Domain Image Processing.pdf
PDF
Network Security Unit 5.pdf for BCA BBA.
PPTX
sap open course for s4hana steps from ECC to s4
PPT
“AI and Expert System Decision Support & Business Intelligence Systems”
PPTX
MYSQL Presentation for SQL database connectivity
PPTX
20250228 LYD VKU AI Blended-Learning.pptx
PDF
NewMind AI Weekly Chronicles - August'25 Week I
PDF
Review of recent advances in non-invasive hemoglobin estimation
PDF
Empathic Computing: Creating Shared Understanding
PPTX
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
PDF
Advanced methodologies resolving dimensionality complications for autism neur...
PDF
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
PDF
Approach and Philosophy of On baking technology
PDF
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
PDF
Per capita expenditure prediction using model stacking based on satellite ima...
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
Dropbox Q2 2025 Financial Results & Investor Presentation
Spectral efficient network and resource selection model in 5G networks
Chapter 3 Spatial Domain Image Processing.pdf
Network Security Unit 5.pdf for BCA BBA.
sap open course for s4hana steps from ECC to s4
“AI and Expert System Decision Support & Business Intelligence Systems”
MYSQL Presentation for SQL database connectivity
20250228 LYD VKU AI Blended-Learning.pptx
NewMind AI Weekly Chronicles - August'25 Week I
Review of recent advances in non-invasive hemoglobin estimation
Empathic Computing: Creating Shared Understanding
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
Advanced methodologies resolving dimensionality complications for autism neur...
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
Approach and Philosophy of On baking technology
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
Per capita expenditure prediction using model stacking based on satellite ima...

Testing untestable code - DPC10

  • 1. Testing untestable Code Stephan Hochdörfer, bitExpert AG "Quality is a function of thought and reflection - precise thought and reflection. That’s the magic." Michael Feathers
  • 2. Agenda 1. About me 2. Theory 3. How to test untestable code 4. Generating testable code 5. Conclusions 6. Questions
  • 3. About me  Stephan Hochdörfer, bitExpert AG  Department Manager Research Labs  enjoying PHP since 1999  S.Hochdoerfer@bitExpert.de  @shochdoerfer
  • 4. No excuse for bad code!
  • 5. Warning! Use at own risk...
  • 6. Theory "There is no secret to writing tests, there are only secrets to write testable code!" Miško Hevery
  • 7. Theory What is „untestable code“?
  • 8. Theory What is „untestable code“?
  • 9. Theory What is „untestable code“?
  • 10. Theory "...our test strategy requires us to have more control or visibility of the internal behavior of the system under test." Gerard Meszaros, xUnit Test Patterns: Refactoring Test Code
  • 11. Theory Required class Class to Unittest Test Required class
  • 12. Theory Database Required class External Class to Unittest resource test Required class Required Required Webservice class class
  • 13. Theory Database Required class External Class to Unittest resource test Required class Required Required Webservice class class
  • 14. Theory How to achieve „testable“ code?
  • 15. Theory How to achieve „testable“ code? Refactoring
  • 16. Theory "Before you start refactoring, check that you have a solid suite of tests." Martin Fowler, Refactoring
  • 17. Testing „untestable“ PHP Code Let the work begin...
  • 18. Testing „untestable“ PHP Code For your safty! Do not change existing code!
  • 19. Testing „untestable“ PHP Code | __autoload <?php class Car { private $Engine; public function __construct($sEngine) { $this->Engine = Engine::getByType($sEngine); } }
  • 20. Testing „untestable“ PHP Code | __autoload <?php class Car { private $Engine; public function __construct($sEngine) { $this->Engine = Engine::getByType($sEngine); } } How to inject a dependency?  Use __autoload
  • 21. Testing „untestable“ PHP Code | __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();
  • 22. Testing „untestable“ PHP Code | include_path <?php include('Engine.php'); class Car { private $Engine; public function __construct($sEngine) { $this->Engine = Engine::getByType($sEngine); } }
  • 23. Testing „untestable“ PHP Code | include_path <?php include('Engine.php'); class Car { private $Engine; public function __construct($sEngine) { $this->Engine = Engine::getByType($sEngine); } } How to inject a dependency?  Manipulate include_path setting
  • 24. Testing „untestable“ PHP Code | 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();
  • 25. Testing „untestable“ PHP Code | include_path alternative <?php class CustomFileStreamWrapper { 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', 'CustomFileStreamWrapper'); return true; } function stream_read($count) {} function stream_write($data) {} function stream_tell() {} function stream_eof() {} function stream_seek($offset, $whence) {} } stream_wrapper_unregister('file'); stream_wrapper_register('file', 'CustomFileStreamWrapper'); Source: Alex Netkachov, http://www.alexatnet.com/node/203
  • 26. Testing „untestable“ PHP Code | include_path alternative <?php class CustomFileStreamWrapper { private $_handler; function stream_open($path, $mode, $options, &$opened_path) { stream_wrapper_restore('file'); $this->_handler = fopen($path, $mode); stream_wrapper_unregister('file'); stream_wrapper_register('file', 'CustomFileStreamWrapper'); return true; } function stream_read($count) { $content = fread($this->_handler, $count); $content = str_replace('Engine::getByType', 'MockedEngine::get', $content); return $content; } } stream_wrapper_unregister('file'); stream_wrapper_register('file', 'CustomFileStreamWrapper'); include('engine.php'); ?>
  • 27. Testing „untestable“ PHP Code | Namespaces <?php class Car { private $Engine; public function __construct($sEngine) { $this->Engine = CarEngine::getByType($sEngine); } }
  • 28. Testing „untestable“ PHP Code | Namespaces <?php class Car { private $Engine; public function __construct($sEngine) { $this->Engine = CarEngine::getByType($sEngine); } } How to inject a dependency?  Use __autoload or manipulate the include_path
  • 29. Testing „untestable“ PHP Code | vfsStream <?php class Car { private $Engine; public function __construct($sEngine, $CacheDir) { $this->Engine = CarEngine::getByType($sEngine); mkdir($CacheDir.'/cache/', 0700, true); } }
  • 30. Testing „untestable“ PHP Code | vfsStream <?php class Car { private $Engine; public function __construct($sEngine, $CacheDir) { $this->Engine = CarEngine::getByType($sEngine); mkdir($CacheDir.'/cache/', 0700, true); } } How mock a filesystem?  Use vfsStream - http://code.google.com/p/bovigo/
  • 31. Testing „untestable“ PHP Code | vfsStream <?php // setup vfsStream vfsStreamWrapper::register(); vfsStreamWrapper::setRoot(new vfsStreamDirectory('app')); $oCar = new Car('Diesel', vfsStream::url('app')); echo vfsStreamWrapper::getRoot()->hasChild('cache');
  • 32. Testing „untestable“ PHP Code „I have no idea how to unit-test procedural code. Unit-testing assumes that I can instantiate a piece of my application in isolation.“ Miško Hevery
  • 33. Testing „untestable“ PHP Code | Test functions <?php function startsWith($sString, $psPre) { return $psPre == substr($sString, 0, strlen($psPre)); } function contains($sString, $sSearch) { return false !== strpos($sString, $sSearch); }
  • 34. Testing „untestable“ PHP Code | Test functions <?php function startsWith($sString, $psPre) { return $psPre == substr($sString, 0, strlen($psPre)); } function contains($sString, $sSearch) { return false !== strpos($sString, $sSearch); } How to test  PHPUnit can call functions  PHPUnit can save/restore globale state
  • 35. Testing „untestable“ PHP Code | overwrite internal functions <?php function buyCar(Car $oCar) { global $oDB; mysql_query("INSERT INTO...", $oDB); mail('order@domain.org', 'New sale', '....'); }
  • 36. Testing „untestable“ PHP Code | overwrite internal functions <?php function buyCar(Car $oCar) { global $oDB; mysql_query("INSERT INTO...", $oDB); mail('order@domain.org', 'New sale', '....'); } How to test  Do not load mysql extension. Provide own implementation  Unfortunatley mail() is part of the PHP core
  • 37. Testing „untestable“ PHP Code | overwrite internal functions <?php function buyCar(Car $oCar) { global $oDB; mysql_query("INSERT INTO...", $oDB); mail('order@domain.org', 'New sale', '....'); } How to test  Use classkit extension to overwrite internal functions
  • 38. Testing „untestable“ PHP Code | overwrite internal functions <?php ini_set('runkit.internal_override', '1'); runkit_function_redefine('mail','','return true;'); ?>
  • 40. Generating testable code Generative Programming
  • 41. Generating testable code Generative Programming Configuration 1 ... n Implementation Generator Product components Generator application
  • 42. Generating testable code Generative Programming Configuration Application Implementation Generator components Testcases Generator application
  • 43. Generating testable code Course of action Extraction  „Mask“ parts of the code Customizing  Change content of global vars  Pre/Postfixes for own functions, methods, classes Recombine  Re-order parts of the code
  • 44. Generating testable code FileFrm FILEIndex_php5 { private String Prefix = "test_"; private String MailSlot = "mail('order@domain.org', 'New sale', '....');"; public FILEIndex_php5() { setFilename("index.php5"); setRelativePath("/"); } private void assign() { BEGINCONTENT() <?php function buyCar(Car $oCar) { global $oDB; <!{Prefix}!>mysql_query(„INSERT INTO...“, $oDB); <!{MailSlot}!> } ?> ENDCONTENT() } }
  • 45. Generating testable code 1. Example Prefix: test_ <?php function buyCar(Car $oCar) { global $oDB; test_mysql_query("INSERT INTO...", $oDB); }
  • 46. Generating testable code 1. Example Prefix: test_ <?php function buyCar(Car $oCar) { global $oDB; test_mysql_query("INSERT INTO...", $oDB); } 2. Example MailSlot: mail('order@domain.org', 'New sale', '....'); <?php function buyCar(Car $oCar) { global $oDB; mysql_query("INSERT INTO...", $oDB); mail('order@domain.org', 'New sale', '....'); } ?>
  • 47. Conclusion How much effort to take?
  • 48. Conclusion Conclusion  Change mindset to write testable code  Dependency Injection  Look for other options to raise the bar  Work around limitations of PHP  PHP is flexible, use it that way