【发布时间】:2021-04-09 03:10:03
【问题描述】:
我在使用 PHPUnit 模拟时遇到问题,当我第二次调用 method()->willReturn() 时,它似乎保持了 setUp 上定义的第一个值:
<?php
namespace Test\Application\UseCase;
use Application\UseCase\CreateFoo;
use Application\Exceptions\RequiredValueException;
use Domain\Entity\Foo;
use PHPUnit\Framework\TestCase;
class CreateFooTest extends TestCase
{
private CreateFoo $sut;
private Foo $foo_spy;
public function setUp()
{
$this->foo_spy = $this->createMock(Foo::class);
$this->foo_spy->method('getBar')->willReturn('bar value');
$this->foo_spy->method('getBaz')->willReturn('baz value');
$this->sut = new CreateFoo;
}
public function test_assert_given_foo_without_bar_throws_exception()
{
// Arrange
$this->expectException(RequiredValueException::class);
$this->expectExceptionMessage('Missing Bar value.');
$this->expectExceptionCode(500);
$this->foo_spy->method('getBar')->willReturn(null);
// var_dump($this->foo_spy->getBar());
// outputs: string(bar value)
// expected: null
// Act, Assert
$this->sut->execute($foo_spy);
}
public function test_assert_given_foo_without_baz_throws_exception()
{
// Arrange
$this->expectException(RequiredValueException::class);
$this->expectExceptionMessage('Missing Baz value.');
$this->expectExceptionCode(500);
$this->foo_spy->method('getBaz')->willReturn(null);
// var_dump($this->foo_spy->getBaz());
// outputs: string(baz value)
// expected: null
// Act, Assert
$this->sut->execute($foo_spy);
}
}
没有在setUp 上定义,我必须重写每个测试的默认值,只是为了测试一个方法调用,如下所示:
$this->foo_spy->method('getBar0')->willReturn('bar value 0');
$this->foo_spy->method('getBar1')->willReturn('bar value 1');
$this->foo_spy->method('getBar2')->willReturn('bar value 2');
$this->foo_spy->method('getBar3')->willReturn('bar value 3');
$this->foo_spy->method('getBaz')->willReturn(null);
问题是:有时我有 10 个或更多属性要测试,这会导致大量不必要的代码重复,所以我想只编写一次默认的 spy mock,然后仅在必要时修改,但正如您所见当我尝试“重置”方法行为时,它没有按预期工作。
【问题讨论】:
标签: php mocking phpunit reset spy