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

标签 php unit-testing laravel testing upload

我正在尝试测试上传 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']));

file path is /public/uploads/test/34610974.jpg

这是我在 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]);

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

最佳答案

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

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

这是一个工作测试的简单示例。它期望您在 tests/stubs 文件夹中有一个 stub test.png 文件。

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)

关于php - 如何在 Laravel 5.2 中测试文件上传,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36408134/

相关文章:

php - 如何避免 file_get_contents 错误 : "Couldn' t resolve host name"

java - junit3 创建测试配置文件 : mock vs real classes

php - Laravel 中的模式表动态添加列

javascript - Laravel Echo - 无法加入状态 channel

php - SQL:如果在另一个表中找不到给定的 ID,则将值插入一个表中(使用单个查询)

php - Laravel 不会读取 PUT 请求的 HTTP 请求负载

php - jQuery 使用延迟加载插件从外部文件加载图像

c# - 有没有办法保护遵循 MethodName_Condition_ExpectedBehaviour 模式的单元测试名称免受重构?

c# - 模拟接口(interface) ReturnsAsync 返回 null

php - Laravel通过smtp服务器发送邮件报错503 5.5.2