簡體   English   中英

如何在 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的實例時,將最后一個參數$testtrue

$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.php
PHPUnit 4.8.24 by Sebastian Bergmann and contributors.

.

Time: 2.97 seconds, Memory: 14.00Mb

OK (1 test, 3 assertions)

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

您可以在此鏈接中找到此代碼

設置

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

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

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM