首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在PHPunit中实现测试替身(站在模拟中),我错过了什么琐碎的东西?

如何在PHPunit中实现测试替身(站在模拟中),我错过了什么琐碎的东西?
EN

Stack Overflow用户
提问于 2012-11-16 00:20:10
回答 1查看 148关注 0票数 1

我可能在这里遗漏了一些非常微不足道的东西,但我不能让phpunit使用替代的模拟类。

下面是一个例子,其中Foo是我正在测试的类,Bar是我想要模拟出来的类。

我希望下面的例子能够通过,因为我已经模拟了Bar,将Bar::heavy_lifting去掉以返回"not bar“,然后将其称为Foo::do_stuff()。然而它失败了,示例仍然返回"bar",似乎完全忽略了我的存根。

代码语言:javascript
复制
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);
  }
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2012-11-16 06:11:18

您的代码将不会按预期工作。存根并不是要替换Bar类,而是要创建可以传递到Bar所期望的位置的对象。你应该像这样重构你的Foo类:

代码语言:javascript
复制
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。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/13401730

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档