如何在 Laravel 5.2 中测试文件上传

2022-08-30 10:31:25

我尝试测试上传 API,但每次都失败:

测试代码 :

$JSONResponse = $this->call('POST', '/upload', [], [], [
    'photo' => new UploadedFile(base_path('public/uploads/test') . '/34610974.jpg', '34610974.jpg')
]);

$this->assertResponseOk();
$this->seeJsonStructure(['name']);

$response = json_decode($JSONResponse);
$this->assertTrue(file_exists(base_path('public/uploads') . '/' . $response['name']));

文件路径为 /public/uploads/test/34610974.jpg

以下是控制器中的我的上传代码:

$this->validate($request, [
    'photo' => 'bail|required|image|max:1024'
]);

$name = 'adummyname' . '.' . $request->file('photo')->getClientOriginalExtension();

$request->file('photo')->move('/uploads', $name);

return response()->json(['name' => $name]);

我应该如何在Laravel 5.2中测试文件上传?如何使用方法上传文件?call


答案 1

创建 的实例时,请将最后一个参数设置为 。UploadedFile$testtrue

$file = new UploadedFile($path, $name, filesize($path), 'image/png', null, true);
                                                                           ^^^^

下面是一个工作测试的快速示例。它期望您在文件夹中有一个存根文件。test.pngtests/stubs

class UploadTest extends TestCase
{
    public function test_upload_works()
    {
        $stub = __DIR__.'/stubs/test.png';
        $name = str_random(8).'.png';
        $path = sys_get_temp_dir().'/'.$name;

        copy($stub, $path);

        $file = new UploadedFile($path, $name, filesize($path), 'image/png', null, true);
        $response = $this->call('POST', '/upload', [], [], ['photo' => $file], ['Accept' => 'application/json']);

        $this->assertResponseOk();
        $content = json_decode($response->getContent());
        $this->assertObjectHasAttribute('name', $content);

        $uploaded = 'uploads'.DIRECTORY_SEPARATOR.$content->name;
        $this->assertFileExists(public_path($uploaded));

        @unlink($uploaded);
    }
}
➔ phpunit tests/UploadTest.php
PHPUnit 4.8.24 by Sebastian Bergmann and contributors.

.

Time: 2.97 seconds, Memory: 14.00Mb

OK (1 test, 3 assertions)

答案 2

在 Laravel 5.4 中,您还可以使用 .下面是一个简单的例子:\Illuminate\Http\UploadedFile::fake()

/**
 * @test
 */
public function it_should_allow_to_upload_an_image_attachment()
{
    $this->post(
        action('AttachmentController@store'),
        ['file' => UploadedFile::fake()->image('file.png', 600, 600)]
    );

    /** @var \App\Attachment $attachment */
    $this->assertNotNull($attachment = Attachment::query()->first());
    $this->assertFileExists($attachment->path());
    @unlink($attachment->path());
}

如果你想伪造一个不同的文件类型,你可以使用

UploadedFile::fake()->create($name, $kilobytes = 0)

更多信息请直接在Laravel文档上。


推荐