0

您将如何对还包含一些逻辑的 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它,那么您将依赖该对象的行为,并且它实际上并不是一个单元测试。

4

1 回答 1

1

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

class InterpreterSpec 
{
    function it_does_something_cool_to_a_context_stub()
    {
        $context = new Context("foo foo");

        $this->intepret($context)->shouldReturn("bar bar");
    }
}
于 2015-04-03T21:32:50.393 回答