我在Symfony 5中编写测试时,在模拟特定对象时返回正确的行为。
我的方法:
public function myTestFunction(TokenInterface $token)
{
$user = $token->getUser();
if (!$user instanceof UserInterface) {
return false;
}
.....
}
我在我的测试中尝试:
$this->token = $this->createMock(TokenInterface::class);
$this->token
->method('getUser')
->willReturn(UserInterface::class);
结果不复制我想要完成基于我发布的代码的行为。
当我将$token定义为存根时,我被迫描述与它的每次交互,否则PHPUnit
将为每个方法调用返回null。
在你的->willReturn
调用中,你应该传递真实的对象而不是类名的字符串。这是我在你当前的代码中看到的错误。
所以你应该创建一个真正的User类,它是UserInterface的一个实例,并将这个对象传递给->willReturn($realUserObject)
。
我想它应该对你有帮助。