yAn*_*Tar 30 testing phpunit deprecated
由于该方法withConsecutive将在 PHPUnit 10 中被删除(在 9.6 中已弃用),我需要将此方法的所有出现替换为新代码。
尝试寻找一些解决方案,但没有找到任何合理的解决方案。
例如,我有一个代码
$this->personServiceMock->expects($this->exactly(2))
->method('prepare')
->withConsecutive(
[$personFirst, $employeeFirst],
[$personSecond, $employeeSecond],
)
->willReturnOnConsecutiveCalls($personDTO, $personSecondDTO);
Run Code Online (Sandbox Code Playgroud)
我应该替换哪个代码withConsecutive?
PS官方网站上的文档仍然显示了如何使用withConsecutive
Awa*_*taq 32
我已将 withConsecutive 替换为以下内容。
$matcher = $this->exactly(2);
$this->service
->expects($matcher)
->method('functionName')
->willReturnCallback(function (string $key, string $value) use ($matcher,$expected1, $expected2) {
match ($matcher->numberOfInvocations()) {
1 => $this->assertEquals($expected1, $value),
2 => $this->assertEquals($expected2, $value),
};
});
Run Code Online (Sandbox Code Playgroud)
Gre*_*reg 14
我刚刚升级到 PHPUnit 10 并遇到了同样的问题。这是我得出的解决方案:
$this->personServiceMock
->method('prepare')
->willReturnCallback(fn($person, $employee) =>
match([$person, $employee]) {
[$personFirst, $employeeFirst] => $personDTO,
[$personSecond, $employeeSecond] => $personSecondDTO
}
);
Run Code Online (Sandbox Code Playgroud)
如果模拟方法传递的内容与块中预期的内容不同match,PHP 将抛出一个UnhandledMatchError.
编辑:一些评论指出了这里的限制,即不知道该函数被调用了多少次。这有点像黑客,但我们可以像这样手动计算函数调用:
// Keep reference of the arguments passed in an array:
$callParams = [];
$this->personServiceMock
->method('prepare')
// Pass the callParams array by reference:
->willReturnCallback(function($person, $employee)use(&$callParams) {
// Store the current arguments in the array:
array_push($callParams, func_get_args());
match([$person, $employee]) {
[$personFirst, $employeeFirst] => $personDTO,
[$personSecond, $employeeSecond] => $personSecondDTO
}
});
// Check that an expected argument call is present in the $callParams array:
self::assertContains(["Person1", "Employee1"], $callParams);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
14314 次 |
| 最近记录: |