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);
}
}
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');
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'));
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);
}
}