在PHPSpec(或任何单元测试框架)中存根一个有状态对象


Stubbing a stateful object in PHPSpec (or any unit testing framework)

您将如何对一个也包含一些逻辑的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();
    }
}

现在,以PHPSpec方式对Interpreter进行单元测试:

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的"真实"实例传递给它,那么您将依赖于对象行为,而这并不是真正的单元测试。

根据我在代码中看到的内容,我不会伪造上下文,而是使用真实的上下文。据我所见,它是一个只访问getter和setter的值对象。

class InterpreterSpec 
{
    function it_does_something_cool_to_a_context_stub()
    {
        $context = new Context("foo foo");
        $this->intepret($context)->shouldReturn("bar bar");
    }
}