当我测试MyCustomClass时, 我在Laravel 7测试中遇到了spy和mock的问题.
我试过在运行$this->get之前使用mock, 在$this->get之后使用spy. 两者都有相同的错误信息(*below).
当在控制器中运行debug时,$myCustomClass仍然是MyCustomClass而不是mocked对象。
MyCustomClass
class MyCustomClass
{
public function execute()
{
return 'hello';
}
MyController
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.
问题是你在实例化 MyCustomClass
身上 new
关键字.
为了让Laravel能够用spy替换掉真正的类, 你必须使用 服务容器.
类似这样
class MyController
{
public function show(MyCustomClass $myCustomClass)
{
return $myCustomClass->execute();
}
}