gpt4 book ai didi

testing - mock 无法计算 Facade 上的方法调用

转载 作者:行者123 更新时间:2023-11-28 21:29:47 27 4
gpt4 key购买 nike

一个根本没有通过的简单测试存在问题。我在 Controller 中有一个 Action :

/**
* @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 方法以防万一你想知道。

最佳答案

终于找到了解决办法。

我没有使用 File 外观,而是通过构造函数注入(inject)了 FileSystem 依赖项,并在单元测试中模拟了它,并将模拟对象传递到 IoC Container ,并且只有这种方式有效,否则在 Laravel 5 上,Mocking Facades 不工作,shouldReceive() 没有像 Laravel Docs 告诉我们的那样保持计数。

亲切的问候

关于testing - mock 无法计算 Facade 上的方法调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27045862/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com