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

当我测试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();
    }
}

本文来自投稿,不代表实战宝典立场,如若转载,请注明出处:https://www.shizhanbaodian.com/19100.html

(0)
上一篇 1天前
下一篇 1天前

相关推荐

发表评论

登录后才能评论