PHPUnit 测试双打
PHPUnit test doubles
我开始使用 PHPUnit 来测试我的代码,但我在理解双重测试方面遇到了一些问题。
我尝试将 class 方法 b 存根为 return true 而不是通常的行为(false),因为另一个方法被调用时
我有这样的代码
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());
}
}
我认为我的第二个断言会奏效,但事实并非如此。我错了,这是不可能的?还有另一种方法可以测试依赖于另一个覆盖其行为的函数吗?
谢谢
当您模拟 class 时,PHPUnit 框架期望您模拟整个 class。您未指定任何 return 值的任何方法将默认为 returning null
(这就是第二个测试失败的原因)。
如果您想模拟方法的子集,请使用 setMethods
函数:
$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());
中的文档中对此进行了说明
我开始使用 PHPUnit 来测试我的代码,但我在理解双重测试方面遇到了一些问题。
我尝试将 class 方法 b 存根为 return true 而不是通常的行为(false),因为另一个方法被调用时
我有这样的代码
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());
}
}
我认为我的第二个断言会奏效,但事实并非如此。我错了,这是不可能的?还有另一种方法可以测试依赖于另一个覆盖其行为的函数吗?
谢谢
当您模拟 class 时,PHPUnit 框架期望您模拟整个 class。您未指定任何 return 值的任何方法将默认为 returning null
(这就是第二个测试失败的原因)。
如果您想模拟方法的子集,请使用 setMethods
函数:
$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());
中的文档中对此进行了说明