您将如何对还包含一些逻辑的 DTO 进行存根(无论如何,哪种方式使其不仅仅是 DTO)?你甚至会存根吗?考虑这个简单的例子:
class Context
{
/**
* @var string
*/
private $value;
function __construct($value)
{
$this->value = $value;
}
public function getValue()
{
return $this->value;
}
public function setValue($value)
{
$this->value = $value;
}
/*
* Some logic that we assume belong here
*/
}
class Interpreter
{
public function interpret(Context $context)
{
$current_context = $context->getValue();
if(preg_match('/foo/', $current_context ))
{
$context->setValue(str_replace('foo', 'bar', $current_context));
$this->interpret();
}
return $context->getValue();
}
}
现在,Interpreter
以 PHPSpec 方式进行单元测试:
class InterpreterSpec
{
function it_does_something_cool_to_a_context_stub(Context $context)
{
$context->getValue()->shouldReturn('foo foo');
$this->intepret($context)->shouldReturn("bar bar");
}
}
显然这会造成无限循环。您将如何对解释器进行单元测试?我的意思是,如果您只是将“真实”实例传递给Context
它,那么您将依赖该对象的行为,并且它实际上并不是一个单元测试。