【问题标题】:Mockery not executing mock method嘲弄不执行模拟方法
【发布时间】:2019-06-26 07:51:30
【问题描述】:

我有类名Validator,它有一个方法forVote。 这是我的代码。

public function test_should_set_default()
    {
        $this->mock = \Mockery::mock(Validator::class);
        $this->mock->shouldReceive('forVote')
            ->andReturnTrue();
        $this->app->instance(Validator::class,$this->mock);
        $factory = new Factory();
        $this->assertTrue($factory->setDefault());
    }

所以Factory 调用Processor,后者调用Validator。现在我想运行模拟验证器。但它调用的是真正的方法。

我做错了什么?

【问题讨论】:

    标签: unit-testing laravel-5 mockery


    【解决方案1】:

    https://laravel.com/docs/5.6/container#introduction

    由于存储库被注入,我们可以轻松地将其换出 与另一个实现。我们也可以轻松地“模拟”,或者 在测试我们的时创建UserRepository 的虚拟实现 应用。

    我的猜测是您目前可能正在像这样实例化您的依赖项:

    $processor = new Processor()$validator = Validator::make(...);

    所以,为了使用你的模拟类,你应该使用依赖注入,这意味着你的类应该通过__construct 方法注入你的依赖。

    你的Factory 类应该是这样的:

    class Factory {
    
       $processor;
    
       public function __construct(Processor $processor)
       {
           $this->processor = $processor;
       }
    
       public function setDefault()
       {
           $this->processor->callingValidator();
       }
    }
    

    和你的Processor 一样:

    class Processor {
    
       $validator;
    
       /**
        * The Validator will resolve to your mocked class.
        *
        */
       public function __construct(Validator $validator)
       {
           $this->validator = $validator;
       }
    
       public function callingValidator()
       {
           $this->validator->make();
       }
    }
    

    【讨论】:

    • 哦..他们就是这样做的,如果不是在构造中实例化依赖项的情况(不作为参数传递)怎么办。那么应该怎么做呢?当我们必须测试控制器时该怎么办?因为我们可以简单地发送http请求和数据?
    • @SachinSharma 应该做的是……你应该重构你的代码以通过构造函数传递它们。 ? 并测试控制器并发送 GET/POST 数据...阅读此内容:laravel.com/docs/5.7/http-tests#testing-json-apis - 如果我的回答有帮助,请将其标记为正确。谢谢。 ?
    猜你喜欢
    • 2018-04-05
    • 2016-07-12
    • 2015-07-17
    • 2017-09-01
    • 2017-12-27
    • 2015-11-13
    • 2015-06-21
    • 2016-12-26
    • 2019-08-10
    相关资源
    最近更新 更多