2

在尝试测试遗留代码库时,我遇到了一个执行以下操作的对象:

class Foo
{
    public function __construct($someargs)
    {
        $this->bar = new Bar();
        // [lots more code]
    }
}

此实例中的 Bar 有一个构造函数,它执行一些坏事,例如连接到数据库。我正试图集中精力测试这个 Foo 类,所以把它改成这样:

class Foo
{
    public function __construct($someargs)
    {
        $this->bar = $this->getBarInstance();
        // [lots more code]
    }

    protected function getBarInstance()
    {
        return new Bar();
    }
}

并尝试通过以下 PHPUnit 测试对其进行测试:

class FooTest extends PHPUnit_Framework_TestCase
{
    public function testInstance()
    {

        $bar = $this->getMock('Bar');
        $foo = $this->getMock('Foo', array('getBarInstance'));
        $foo->expects($this->any())
            ->method('getBarInstance')
            ->will($this->returnValue($bar));

    }

}

但是这不起作用 - Foo() 的构造函数在我的 ->expects() 被添加之前被调用,所以模拟的 getBarInstance() 方法返回一个空值。

有没有什么方法可以解除这种依赖关系,而不必重构类使用构造函数的方式?

4

1 回答 1

4

使用 的$callOriginalConstructor论点getMock()。将其设置为false。这是该方法的第五个参数。在这里查找:http ://www.phpunit.de/manual/current/en/api.html#api.testcase.tables.api

其实,等一下。您想将模拟传递给模拟吗?如果你真的想要这个,那么使用它的第三个参数getMock代表构造函数的参数。在那里你可以将模拟传递给Bar模拟Foo

于 2009-09-15T15:06:21.407 回答