2. Testing untestable code
About me
Stephan Hochdörfer, bitExpert AG
Department Manager Research Labs
enjoying PHP since 1999
S.Hochdoerfer@bitExpert.de
@shochdoerfer
13. Testing untestable code
"...our test strategy requires us to
have more control [...] of the sut."
Gerard Meszaros, xUnit Test Patterns: Refactoring Test
Code
25. Testing untestable code
Object construction
<?php
class Car {
private $Engine;
public function __construct($sEngine) {
$this->Engine = Engine::getByType($sEngine);
}
}
27. Testing untestable code
Object construction
<?php
include('Engine.php');
class Car {
private $Engine;
public function __construct($sEngine) {
$this->Engine = Engine::getByType($sEngine);
}
}
32. Testing untestable code
Object construction – Namespaces
<?php
class Car {
private $Engine;
public function __construct($sEngine) {
$this->Engine = CarEngine::
getByType($sEngine);
}
}
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');
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'));
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);
}
}