PHPUnit 测试双打 [英] PHPUnit test doubles
问题描述
我开始使用 PHPUnit 来测试我的代码,但我在理解双重测试方面遇到了一些问题.
I am starting to use PHPUnit for test my code but I have some problems with understand double tests.
当被另一个方法调用时,我尝试存根类方法 b 以返回 true 而不是通常的行为 (false)
I try to stub a class method b to return true instead of usual behavior (false) when is called since another method
我有一个这样的代码
class MyClass {
function a()
{
return $this->b();
}
function b()
{
return false;
}
}
class MyClassTest extends TestCase
{
function testAThrowStubB()
{
$myClassStub = $this->getMockBuilder('\MyClass')
->getMock();
$myClassStub->expects($this->any())
->method('b')
->willReturn(true);
// this assert will work
$this->assertTrue($myClassStub->b());
// this assert will fail
$this->assertTrue($myClassStub->a());
}
}
我以为我的第二个断言会起作用,但它不起作用.我错了,这是不可能的?还有另一种方法可以测试依赖于另一个覆盖其行为的函数吗?
I thought my second assertion will work but it doesn't. I'm wrong and it is not possible? There is another way to test a function who depends on another overriding his behavior?
谢谢
推荐答案
当您模拟一个类时,PHPUnit 框架期望您模拟整个类.您未指定任何返回值的任何方法将默认返回 null
(这就是第二个测试失败的原因).
When you mock a class the PHPUnit framework expects that you're mocking the entire class. Any methods for which you don't specify any return values will default to returning null
(which is why the second test was failing).
如果您想模拟方法的子集,请使用 setMethods
函数:
If you want to mock a subset of methods use the setMethods
function:
$myClassStub = $this->getMockBuilder(MyClass::class)
->setMethods(["b"])
->getMock();
$myClassStub->expects($this->any())
->method('b')
->willReturn(true);
// this assert will work
$this->assertTrue($myClassStub->b());
// this assert will work too
$this->assertTrue($myClassStub->a());
这在 示例 9.11
这篇关于PHPUnit 测试双打的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!