How to test file upload in Laravel 5.2

时间:2016-04-04 16:35:12

标签: php unit-testing laravel testing upload

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

file path is /public/uploads/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?

5 个答案:

答案 0 :(得分:48)

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

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

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

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)

答案 1 :(得分:12)

在Laravel 5.4中,您也可以使用(batch_size, 1, 1, NUM_CHANNELS)。下面是一个简单的例子:

git rebase -p -i <blah>

如果您想伪造其他文件类型,可以使用

pick A
pick B  <- merge commit to ammend
fixup D
pick C

直接在Laravel Documentation上提供更多信息。

答案 2 :(得分:2)

我认为这是最简单的方法

$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");
}

答案 3 :(得分:0)

您可以在此link

找到此代码

<强>设置

/**
 * @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

答案 4 :(得分:0)

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

}