我可能在这里遗漏了一些非常微不足道的东西,但我不能让phpunit使用替代的模拟类。
下面是一个例子,其中Foo是我正在测试的类,Bar是我想要模拟出来的类。
我希望下面的例子能够通过,因为我已经模拟了Bar,将Bar::heavy_lifting去掉以返回"not bar“,然后将其称为Foo::do_stuff()。然而它失败了,示例仍然返回"bar",似乎完全忽略了我的存根。
class Foo {
public function do_stuff() {
$b = new Bar();
return $b->heavy_lifting();
}
}
class Bar {
public function heavy_lifting() {
return "bar";
}
}
class FooTest extends PHPUnit_Framework_TestCase {
public function testBar() {
$fake = "not bar";
$stand_in = $this->getMock("Bar");
$stand_in->expects($this->any())
->method("heavy_lifting")
->will($this->returnValue($fake));
$foo = new Foo();
$this->assertEquals($foo->do_stuff(), $fake);
}
}发布于 2012-11-16 06:11:18
您的代码将不会按预期工作。存根并不是要替换Bar类,而是要创建可以传递到Bar所期望的位置的对象。你应该像这样重构你的Foo类:
class Foo {
/* inject your dependency to Foo, it can be injected in many ways,
using constructor, setter, or DI Container */
public function __construct(Bar $bar) {
$this->bar = $bar;
}
public function do_stuff() {
$this->bar->heavy_lifting();
}
}然后您可以将mocked Bar传递给类Foo。
https://stackoverflow.com/questions/13401730
复制相似问题