【问题标题】:Mockery not being able to count method calls on a FacadeMockery 无法计算 Facade 上的方法调用
【发布时间】:2015-01-18 16:25:04
【问题描述】:

一个根本没有通过的简单测试存在问题。 我在控制器中有一个动作:

/**
 * @Get("/parse")
 * @param Dispatcher $dispatcher
 * @return string
 */
public function parse(){
    $xml_file = public_path()."/dummy.xml";
    //File::get($xml_file); Tried this as well
    $file = $this->file->get($xml_file);
    return $file;
}

在测试中我有一个类似的方法:

/**
 * A basic functional test example.
 *
 * @return void
 */
public function testBasicExample(){
        File::shouldReceive("get")->once();
        $this->call('GET', '/parse');
}

在 Laravel 文档中,他们说每个 Facade 都可以直接模拟,无需实例化,但测试永远不会通过,我遇到了一个异常:

Mockery\Exception\InvalidCountException: Method get() from Mockery_0 should be called exactly 1 times but called 0 times.

PS:我有 Laravel 5,在测试类中我有 tearDown 方法,以防你想知道。

【问题讨论】:

  • 如何将$this->file 注入控制器?
  • 通过构造函数,Laravel 由 Depency Injector 完成其余的工作,但是如果我尝试使用 File::get() 则这将无法正常工作
  • 当然是通过构造函数,我的意思是你在ServiceProvider中绑定的代码。
  • 这是一个默认的 Laravel Facade,具有别名 File,它从 IoC 解析 Illuminate\Filesystem\Filesystem

标签: testing laravel phpunit mockery laravel-5


【解决方案1】:

终于找到了解决办法。

我没有使用 File,facade,而是通过构造函数注入 FileSystem 依赖项,并在单元测试中对其进行了模拟,并将模拟的对象传递给 IoC 容器,仅此而已工作,否则在 Laravel 5 上,Mocking Facades 不起作用,shouldReceive() 没有像 Laravel Docs 告诉我们的那样计数。

亲切的问候

【讨论】:

    猜你喜欢
    • 2014-03-11
    • 2022-01-04
    • 2017-02-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多