首先验证响应状态码为200,再检查Content-Type和Content-Disposition响应头是否正确,最后确认文件内容返回无误;使用Storage::fake()模拟文件确保测试稳定性,同时需测试文件不存在时返回404的情况。

在 laravel 中测试文件下载响应,核心是验证响应的 http 状态码、响应头(特别是 Content-Type 和 Content-Disposition)以及是否正确返回了文件内容。Laravel 提供了强大的测试工具来模拟请求并断言响应行为。
1. 创建一个文件下载路由和控制器方法
假设你有一个路由用于下载存储在 storage/app/public/files/example.pdf 的文件:
Route::get('/download', [FileController::class, 'download']);
控制器方法可能如下:
public function download() { $path = storage_path('app/public/files/example.pdf'); if (!file_exists($path)) { abort(404); } return response()->download($path, 'example.pdf', [ 'Content-Type' => 'application/pdf' ]); }
2. 编写测试用例
使用 Laravel 的测试框架,在 tests/Feature 目录下创建测试类(如 DownloadTest.php),并通过 $this->get() 发起请求,然后进行断言。
示例测试代码:
use IlluminateFoundationTestingRefreshDatabase; use IlluminateSupportFacadesStorage; use TestsTestCase; class DownloadTest extends TestCase { use RefreshDatabase; public function test_can_download_file() { // 确保存在测试文件(可选:使用 Storage facade 模拟) Storage::fake('public'); Storage::disk('public')->put('files/example.pdf', 'dummy content for testing'); $response = $this->get('/download'); $response->assertStatus(200) ->assertHeader('Content-Type', 'application/pdf') ->assertHeader('Content-Disposition', 'attachment; filename="example.pdf"') ->assertSee('dummy content for testing'); // 如果是文本文件可用 } }
3. 关键断言说明
- assertStatus(200):确保请求成功,没有返回 404 或 500 错误。
- assertHeader(‘Content-Type’, ‘…’):验证响应头中的 MIME 类型是否正确(如 pdf、xlsx、zip 等)。
- assertHeader(‘Content-Disposition’, ‘…’):确认响应头包含
attachment,表示浏览器应下载而非预览,并检查文件名是否正确。 - assertSee(…):如果文件是文本类型(如 .txt、.csv),可以检查部分内容。二进制文件(如 PDF、图片)不适用此方法。
4. 使用 Storage Facade 模拟文件(推荐做法)
避免依赖真实文件系统,使用 Laravel 的 Storage::fake() 来模拟文件存在:
Storage::fake('public'); Storage::disk('public')->put('files/report.xlsx', 'test excel data');
这样测试更稳定,不依赖本地文件,也适合 CI/CD 环境。
5. 测试文件不存在的情况
你也应该测试当文件不存在时是否返回 404:
public function test_returns_404_when_file_not_found() { // 不创建文件 $response = $this->get('/download'); $response->assertStatus(404); }
基本上就这些。只要验证好状态码、响应头和文件模拟,就能可靠地测试 Laravel 的文件下载功能。