控制器中自定义 class 的嘲笑模拟和间谍调用 0 次
Mockery mock and spy called 0 times on custom class in controller
我在测试 MyCustomClass 时遇到了 Laravel 7 测试中的间谍和模拟问题。
我试过在 运行 $this->get 之前模拟和在 $this->get 之后监视。两者都有相同的错误消息(*下方)。
当 运行 在控制器中调试时,$myCustomClass 仍然是 MyCustomClass 而不是模拟对象。
MyCustomClass
class MyCustomClass
{
public function execute()
{
return 'hello';
}
我的控制器
class MyController
{
public function show()
{
$myCustomClass = new MyCustomClass();
$data = $myCustomClass->execute();
return $data;
}
private $mySpy;
public function testAMethod()
{
$spy = $this->spy(MyCustomClass::class);
$response = $this->get('/my/path');
$spy->shouldHaveReceived('execute');
$response->assertStatus(200);
}
错误
Method execute(<Any Arguments>) from Mockery_2_App_MyCustomClass should be called
at least 1 times but called 0 times.
问题是您正在使用 new
关键字实例化自己 MyCustomClass
。
为了 Laravel 能够用间谍交换真正的 class 你必须使用 service container.
像这样:
class MyController
{
public function show(MyCustomClass $myCustomClass)
{
return $myCustomClass->execute();
}
}
我在测试 MyCustomClass 时遇到了 Laravel 7 测试中的间谍和模拟问题。
我试过在 运行 $this->get 之前模拟和在 $this->get 之后监视。两者都有相同的错误消息(*下方)。
当 运行 在控制器中调试时,$myCustomClass 仍然是 MyCustomClass 而不是模拟对象。
MyCustomClass
class MyCustomClass
{
public function execute()
{
return 'hello';
}
我的控制器
class MyController
{
public function show()
{
$myCustomClass = new MyCustomClass();
$data = $myCustomClass->execute();
return $data;
}
private $mySpy;
public function testAMethod()
{
$spy = $this->spy(MyCustomClass::class);
$response = $this->get('/my/path');
$spy->shouldHaveReceived('execute');
$response->assertStatus(200);
}
错误
Method execute(<Any Arguments>) from Mockery_2_App_MyCustomClass should be called
at least 1 times but called 0 times.
问题是您正在使用 new
关键字实例化自己 MyCustomClass
。
为了 Laravel 能够用间谍交换真正的 class 你必须使用 service container.
像这样:
class MyController
{
public function show(MyCustomClass $myCustomClass)
{
return $myCustomClass->execute();
}
}