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

Ram*_*min 35 php testing upload unit-testing laravel

我试图测试上传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']));
Run Code Online (Sandbox Code Playgroud)

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

这是控制器中的My Upload代码:

$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]);
Run Code Online (Sandbox Code Playgroud)

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

pet*_*erm 51

当您创建的实例UploadedFile设置的最后一个参数$testtrue.

$file = new UploadedFile($path, $name, filesize($path), 'image/png', null, true);
                                                                           ^^^^
Run Code Online (Sandbox Code Playgroud)

这是一个工作测试的快速示例.它希望您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);
    }
}
Run Code Online (Sandbox Code Playgroud)
? 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)

  • 它应该是`$ file = new UploadedFile($ path,$ name,'image/png',filesize($ path),null,true);` (6认同)

MiC*_*c83 12

在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());
}
Run Code Online (Sandbox Code Playgroud)

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

UploadedFile::fake()->create($name, $kilobytes = 0)
Run Code Online (Sandbox Code Playgroud)

有关Laravel文档的更多信息.