Is it OK to introduce methods that are used only during unit tests?
Posted
by
Mchl
on Programmers
See other posts from Programmers
or by Mchl
Published on 2011-06-24T19:25:12Z
Indexed on
2011/06/25
0:31 UTC
Read the original article
Hit count: 186
TDD
|factory-method
Recently I was TDDing a factory method. The method was to create either a plain object, or an object wrapped in a decorator. The decorated object could be of one of several types all extending StrategyClass.
In my test I wanted to check, if the class of returned object is as expected. That's easy when plain object os returned, but what to do when it's wrapped within a decorator?
I code in PHP so I could use ext/Reflection
to find out a class of wrapped object, but it seemed to me to be overcomplicating things, and somewhat agains rules of TDD.
Instead I decided to introduce getClassName()
that would return object's class name when called from StrategyClass. When called from the decorator however, it would return the value returned by the same method in decorated object.
Some code to make it more clear:
interface StrategyInterface {
public function getClassName();
}
abstract class StrategyClass implements StrategyInterface {
public function getClassName() {
return \get_class($this);
}
}
abstract class StrategyDecorator implements StrategyInterface {
private $decorated;
public function __construct(StrategyClass $decorated) {
$this->decorated = $decorated;
}
public function getClassName() {
return $this->decorated->getClassName();
}
}
And a PHPUnit test
/**
* @dataProvider providerForTestGetStrategy
* @param array $arguments
* @param string $expected
*/
public function testGetStrategy($arguments, $expected) {
$this->assertEquals(
__NAMESPACE__.'\\'.$expected,
$this->object->getStrategy($arguments)->getClassName()
)
}
//below there's another test to check if proper decorator is being used
My point here is: is it OK to introduce such methods, that have no other use than to make unit tests easier? Somehow it doesn't feel right to me.
© Programmers or respective owner