11. Testing untestable code
"...our test strategy requires us to
have more control [...] of the sut."
Gerard Meszaros, xUnit Test Patterns: Refactoring Test
Code
23. Testing untestable code
Object construction
public class Car {
private Engine engine;
public Car(String engine) {
this.engine = EngineFactory.getByType(engine);
}
}
24. Testing untestable code
Object construction - Solution
public class MyLoader extends ClassLoader {
protected Class findClass(String name)
throws ClassNotFoundException
{
try {
String path = name.replace('.', '/');
// @TODO: change path and read file,
// @TODO: define package
// @TODO: define class
}
catch(Exception e){
throw new ClassNotFoundException(name);
}
}
}
25. Testing untestable code
Object construction - Solution II
<?php
class MyStreamWrapper {
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', 'MyStreamWrapper');
return true;
}
}
37. 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');
48. Testing untestable code
Generative Programming
A frame is a data structure
for representing knowledge.
49. Testing untestable code
A Frame instance
public class Car {
private Engine engine;
public Car(String engine) {
this.engine = <!{Factory}!>.getByType(engine);
}
}
50. 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");
}
}
}
51. Testing untestable code
Generated result - Testcase
public class Car {
private Engine engine;
public Car(String engine) {
this.engine = FactoryMock.getByType(engine);
}
}
52. Testing untestable code
Generated result - Application
public class Car {
private Engine engine;
public Car(String engine) {
this.engine = EngineFactory.getByType(engine);
}
}