如何向被测类添加模拟期望
要测试的代码
abstract class Parent
{
public function getSomething(){} //this has to be mocked
}
class Child extends Parent
{
public function methodWhichIsTested()
{
$something = $this->getSomething(); //call to parent method
}
}
测试
public function setUp()
{
$this->child = new Child;
}
public function testTheChildMethod()
{
$this->child->methodWhichIsTested();
}
如何将模拟期望添加到实例化的类 Child 中? 我想做类似的事情:
MockFramework->takeExistingClass('Child')->shouldRecieve('getSomething')->andReturn('whatever');
我的问题是,在实际情况(不是示例)中, getSomething 方法返回一个依赖项,我需要模拟它!
我正在使用 Mockery 但如果你知道如何使用 phpUnit 模拟来做到这一点,继续吧!也许我犯了一个基本的思维错误,请帮帮我!谢谢。
The code to be tested
abstract class Parent
{
public function getSomething(){} //this has to be mocked
}
class Child extends Parent
{
public function methodWhichIsTested()
{
$something = $this->getSomething(); //call to parent method
}
}
The test
public function setUp()
{
$this->child = new Child;
}
public function testTheChildMethod()
{
$this->child->methodWhichIsTested();
}
How can I add mock expectations to the instantiated class Child?
I would like to do something like:
MockFramework->takeExistingClass('Child')->shouldRecieve('getSomething')->andReturn('whatever');
My problem is, that in the real case (not the example), the getSomething method returns a dependency, which I need to mock!
I am using Mockery but if you know how to do this with phpUnit mocks, go ahead! Maybe I'm making a basic thinking mistake, please give me a hand! Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在聊天中澄清后,
getSomething
的返回值包含一个依赖项是解决方案是通过该其他方法注入该依赖项的模拟。
一般来说,您永远不需要模拟或存根 TestSubject 的行为。只有当您查找全局范围或将混合/硬代码对象创建到 TestSubject 中时,您可能会看到这样做的必要性,但这些将是代码味道,应该进行重构。请参阅 Sebastian Bergmann 关于不可测试代码的文章:
After you clarfied in chat that the returned value of
getSomething
holds a dependency that isthe solution is inject a mock of that dependency via that other method.
In general, you should never have the need to mock or stub behavior of the TestSubject. It is only when you are making lookups to the Global Scope or mix/hard code object creation into the TestSubject, that you might see the need for that, but these would be code smells and should be refactored instead. See Sebastian Bergmann's articles on untestable code: