我刚刚开始使用 PHPUnit,我想知道是否可以用 stub 覆盖/替换方法。我有一些使用Sinon的经验,使用Sinon这是可能的( http://sinonjs.org/docs/#stubs )
我想要这样的东西:
<?php
class Foo {
public $bar;
function __construct() {
$this->bar = new Bar();
}
public function getBarString() {
return $this->bar->getString();
}
}
class Bar {
public function getString() {
return 'Some string';
}
}
class FooTest extends PHPUnit_Framework_TestCase {
public function testStringThing() {
$foo = new Foo();
$mock = $this->getMockBuilder( 'Bar' )
->setMethods(array( 'getString' ))
->getMock();
$mock->method('getString')
->willReturn('Some other string');
$this->assertEquals( 'Some other string', $foo->getBarString() );
}
}
?>
最佳答案
这不起作用,您将无法在 Foo 实例内模拟 Bar 实例。 Bar 在 Foo 的构造函数内实例化。
更好的方法是将 Foo 的依赖注入(inject)到 Bar,即。例如:
<?php
class Foo {
public $bar;
function __construct(Bar $bar) {
$this->bar = $bar;
}
public function getBarString() {
return $this->bar->getString();
}
}
class Bar {
public function getString() {
return 'Some string';
}
}
class FooTest extends PHPUnit_Framework_TestCase {
public function testStringThing() {
$mock = $this->getMockBuilder( 'Bar' )
->setMethods(array( 'getString' ))
->getMock();
$mock->method('getString')
->willReturn('Some other string');
$foo = new Foo($mock); // Inject the mocked Bar instance to Foo
$this->assertEquals( 'Some other string', $foo->getBarString() );
}
}
参见http://code.tutsplus.com/tutorials/dependency-injection-in-php--net-28146 DI 的小教程。
关于PHPUnit 用 stub 覆盖实际方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28419169/