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

Test Code :

$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/ploads/test/34610974.jpg

Here is My Upload code in a controller :

$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]);

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

推荐答案

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);
                                                                           ^^^^

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相关问答推荐

灯丝:设定模式标题

如何在Laravel中创建自定义单项集合

Laravel 9 中使用 WHERE 子句的列的 SUM

如何避免谷歌翻译翻译:参数

Laravel - 出于某种原因,max 打破了我的查询

Laravel API 版本控制文件夹 struct

Laravel PHP 框架的新手. /以外的路由不起作用

上传时Laravel正在旋转图像

使用 Eloquent 的 Laravel 块方法

在 laravel 如何将额外的数据传递给 mutators 和 accessors

artisan 迁移错误找不到类'Doctrine\\DBAL\\Driver\\PDOMySql\\Driver'

Laravel 生产问题 - 使用 Laravel 4.1.x 更新composer

不支持驱动Driver[] - Laravel 5.3

如何从不是控制器方法的方法发送响应?

如何更改默认 Laravel Auth 登录视图

Laravel:命令未找到

为什么在 Laravel 的 DB::select 中使用 DB::raw?

Laravel 项目旁边的 Wordpress 项目(在 public_html 文件夹中)

Laravel 5 默认注册后如何发送邮件?

Laravel 更新后用户模型错误(用户类包含 3 个抽象方法)