在尝试测试遗留代码库时,我遇到了一个执行以下操作的对象:
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() 方法返回一个空值。
有没有什么方法可以解除这种依赖关系,而不必重构类使用构造函数的方式?