sb8*_*b89 8 phpunit unit-testing laravel mockery laravel-4
我的其中一条路线中有以下代码:
return Response::download('cv.pdf');
知道如何测试这个吗?我试过使用 shouldReceive() 但这似乎不起作用('shouldReceive() 未定义函数......')。
Tan*_*may 14
$response->assertDownload()Laravel 8.45.0 中添加:
断言响应是“下载”。通常,这意味着返回响应的调用路由返回了 Response::download 响应、BinaryFileResponse 或 Storage::download 响应:
$response->assertDownload();
了解更多:
https://laravel.com/docs/8.x/http-tests#assert-download
目前(2023 年)它不允许测试文件的内容,但您可以为此使用测试模拟:
public function test_successful_download(): void
{
$this->authenticateAsAdmin();
$this->instance(
ResponseFactory::class,
Mockery::mock(ResponseFactory::class, static function(MockInterface $mock) {
$mock
->shouldReceive('download')
->with('[[ FILE CONTENTS ]]', '[[ FILE NAME]]')
->once()
;
}),
);
$this->call('POST', route('my-download-csv'));
}
Run Code Online (Sandbox Code Playgroud)
# mycontroller.php
// ...
public function downloadCsv(Request $request)
{
return response()->download('[[ FILE CONTENTS ]]', '[[ FILE NAME]]');
}
// ...
Run Code Online (Sandbox Code Playgroud)
OK (1 test, 1 assertion)
Run Code Online (Sandbox Code Playgroud)
编辑:正如@DavidBarker 在对 OP 问题的评论中指出的那样
Illuminate\Support\Facades\Response 类实际上并未扩展 Illuminate\Support\Facades\Facade,因此没有 shouldRecieve() 方法。在测试中调用该路由后,您需要测试该路由的响应。
因此,如果您想测试下载功能,可以尝试使用以下命令检查响应是否有错误:
$this->assertTrue(preg_match('/(error|notice)/i', $response) === false);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7048 次 |
| 最近记录: |