如何使用表单验证测试Laravel媒体上传



前段时间,我在Laravel项目中为我的媒体上传编写了一个测试。测试只是将带有图像的 post 请求发送到路由,并检查服务器是否发送 200 状态代码。

use IlluminateHttpUploadedFile;
/** @test */
public function it_can_upload_image()
{
$response = $this->post('/media', [
'media' => new UploadedFile(__DIR__ . "/test_png.png", 'test_png.png'),
]);
$response->assertStatus(200);
}

当我为mediapost 参数添加验证规则时,服务器返回 302 状态代码,测试失败。但是,当我在浏览器中手动测试媒体上传时,一切正常。

public function uplaodMedia($request) 
{
$request->validate([
'media' => 'required'
]);
// ...
}

测试中请求的行为似乎与实际的浏览器请求不同。但是,直到现在我还没有设法解决这个问题。以前有人遇到过类似的事情吗?

在为测试创建新UploadedFile时,您需要为$test参数传递true

new UploadedFile(__DIR__ . "/test_png.png", 'test_png.png', null, null, true)

在这里你可以找到构造函数定义:

/**
* @param bool        $test         Whether the test mode is active
*                                  Local files are used in test mode hence the code should not enforce HTTP uploads
*/
public function __construct(string $path, string $originalName, string $mimeType = null, int $error = null, bool $test = false)

虽然我不明白为什么要在此测试中使用真实图像,但Laravel提供了一种内置的方式来轻松测试文件上传。

从文档中:

存储门面的假方法可让您轻松生成假货 磁盘,与 上传文件类,大大简化了文件上传的测试。

因此,您的测试可以简化为以下内容:

use IlluminateHttpUploadedFile;
use IlluminateSupportFacadesStorage;
/** @test */
public function it_can_upload_image()
{        
Storage::fake();
$this->post('/media', ['media' => UploadedFile::fake()->image('test_png.png')])
->assertStatus(200);
}

最新更新