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

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));

    }

}

但是这不起作用 - 在我的 - > expected()被添加之前调用Foo()的构造函数,因此模拟的getBarInstance()方法返回null。

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

有帮助吗?

解决方案

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

实际上,坚持下去。你想将模拟传递给模拟?如果你真的想要这个,那么使用 getMock 的第三个参数来表示构造函数的参数。在那里你可以将 Bar 的模拟传递给 Foo 的模拟。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top