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


How to test file upload in Laravel 5.2

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

文件路径为/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方法上传文件?

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

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

下面是一个工作测试的快速示例。它希望您在tests/stubs文件夹中有一个存根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由Sebastian Bergmann和贡献者撰写。。时间:2.97秒,内存:14.00MbOK(1个测试,3个断言)

在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());
}

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

UploadedFile::fake()->create($name, $kilobytes = 0)

更多信息请直接访问Laravel文档。

我认为这是最简单的方法

$file=UploadedFile::fake()->image('file.png', 600, 600)];
$this->post(route("user.store"),["file" =>$file));
$user= User::first();
//check file exists in the directory
Storage::disk("local")->assertExists($user->file); 

我认为在测试中删除上传文件的最好方法是使用tearDownAfterClass静态方法,这将删除所有上传的文件

use Illuminate'Filesystem'Filesystem;
public static function tearDownAfterClass():void{
        $file=new Filesystem;
        $file->cleanDirectory("storage/app/public/images");
}

当您想要测试一个假文件时,laravel文档有一个答案。当你想在laravel 6中使用真实文件进行测试时,你可以做以下操作:

namespace Tests'Feature;
use Illuminate'Http'UploadedFile;
use Tests'TestCase;
class UploadsTest extends TestCase
{
    // This authenticates a user, useful for authenticated routes
    public function setUp(): void
    {
        parent::setUp();
        $user = User::first();
        $this->actingAs($user);
    }    
    public function testUploadFile()
    {
        $name = 'file.xlsx';
        $path = 'absolute_directory_of_file/' . $name;
        $file = new UploadedFile($path, $name, 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', null, true);
        $route = 'route_for_upload';
        // Params contains any post parameters
        $params = [];
        $response = $this->call('POST', $route, $params, [], ['upload' => $file]);
        $response->assertStatus(200);
    }  
}

您可以在链接中找到此代码

设置

/**
 * @param      $fileName
 * @param      $stubDirPath
 * @param null $mimeType
 * @param null $size
 *
 * @return  'Illuminate'Http'UploadedFile
 */
public static function getTestingFile($fileName, $stubDirPath, $mimeType = null, $size = null)
{
    $file =  $stubDirPath . $fileName;
    return new 'Illuminate'Http'UploadedFile'UploadedFile($file, $fileName, $mimeType, $size, $error = null, $testMode = true);
}

用法

    $fileName = 'orders.csv';
    $filePath = __DIR__ . '/Stubs/';
    $file = $this->getTestingFile($fileName, $filePath, 'text/csv', 2100);

文件夹结构:

- MyTests
  - TestA.php
  - Stubs
    - orders.csv