gpt4 book ai didi

PHPUnit 测试 double

转载 作者:可可西里 更新时间:2023-11-01 01:13:36 24 4
gpt4 key购买 nike

我开始使用 PHPUnit 来测试我的代码,但我在理解双重测试方面遇到了一些问题。

我尝试对类方法 b 进行 stub 以在自另一个方法调用时返回 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());
}
}

我认为我的第二个断言会奏效,但事实并非如此。我错了,这是不可能的?还有另一种方法可以测试依赖于另一个覆盖他行为的函数吗?

谢谢

最佳答案

当您模拟一个类时,PHPUnit 框架希望您模拟整个类。您未为其指定任何返回值的任何方法都将默认返回 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());

这在 example 9.11 的文档中有说明。

关于PHPUnit 测试 double ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46192311/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com