如何在Laravel 5.2中测试文件上传 [英] How to test file upload in Laravel 5.2

查看:79
本文介绍了如何在Laravel 5.2中测试文件上传的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Im trying to test an upload API but it fails every time:

测试代码:

$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

file path is /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方法上传文件?

How should I test file upload in Laravel 5.2? How to use call method to upload a file?

推荐答案

创建UploadedFile的实例时,将最后一个参数$test设置为true.

When you create an instance of UploadedFile set the last parameter $test to true.

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

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

Here is a quick example of a working test. It expects that you have a stub test.png file in tests/stubs folder.

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)

这篇关于如何在Laravel 5.2中测试文件上传的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆