在尝试测试遗留代码库时,我遇到了一个执行以下操作的对象:
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() 方法返回 null。
是否有任何方法可以取消这种依赖关系,而不必重构类使用构造函数的方式?
最佳答案
使用getMock()
的$callOriginalConstructor
参数。将其设置为false
。这是该方法的第五个参数。在这里查找:http://www.phpunit.de/manual/current/en/api.html#api.testcase.tables.api
其实,等等。你想将模拟传递给模拟吗?如果您确实想要这样做,请使用 getMock 的第三个参数,它代表构造函数的参数。在那里,您可以将 Bar
的模拟传递给 Foo
的模拟。
关于php - 使用 PHPunit 删除构造函数中的依赖项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1427738/