在controller中的自定义类上调用了0次Mockery mock和spy。

问题描述 投票:1回答:1

当我测试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.
php laravel testing mockery
1个回答
1
投票

问题是你在实例化 MyCustomClass 身上 new 关键字.

为了让Laravel能够用spy替换掉真正的类, 你必须使用 服务容器.

类似这样

class MyController
{
    public function show(MyCustomClass $myCustomClass)
    {
        return $myCustomClass->execute();
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.