gpt4 book ai didi

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

转载 作者:IT王子 更新时间:2023-10-29 01:02:09 25 4
gpt4 key购买 nike

我正在尝试测试上传 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.phpPHPUnit 4.8.24 by Sebastian Bergmann and contributors..Time: 2.97 seconds, Memory: 14.00MbOK (1 test, 3 assertions)

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com