如何在laravel中为文件上传功能创建phpunit测试用例



Controller.php

public function uploadDocument($request,$profileId)
{
$s3Bucket = 's3.' . $request->input('fileType');
$file = $request->file('document');
$name = $file->hashName();
}

Testcase.php


use IlluminateHttpRequest;
use Mockery;
use IlluminateHttpUploadedFile;
use PHPUnitFrameworkTestCase;
public function testUploadDocumentSuccess()
{
$test = new IlluminateHttpUploadedFile(public_path('laravel-test-img.jpg'), 'laravel-test-img.jpg', 'image/jpg', 
filesize(public_path() . '/laravel-test-img.jpg'), true);
$request = new Request([
'fileType' => 'profile',    
'document' => $test
]);

$response = $this->documentService->uploadDocument($request, 1);
$this->assertIsArray($response);
}

对于进行单元测试,使用mock对象来调用每个类。不通过传递路由名称直接调用端点。

查询

通过测试用例函数传递的请求对象访问文件数据时,总是从$request->file('docuemnt')获取null。

我已经尝试了很多方法,并在网上找到了解决方案,但最重要的是,通过像一样亲自调用路线来提供解决方案

$response = $this->action(
'POST',
'FileStorageController@store',
$values,
['file' => $uploadedFile]
);

您可能会探索通过mock()方法来模拟文件。你可以在这里找到更多https://laravel.com/docs/9.x/mocking#storage-假的。

Laravel提供的样品:

<?php

namespace TestsFeature;

use IlluminateFoundationTestingRefreshDatabase;
use IlluminateFoundationTestingWithoutMiddleware;
use IlluminateHttpUploadedFile;
use IlluminateSupportFacadesStorage;
use TestsTestCase;

class ExampleTest extends TestCase
{
public function test_albums_can_be_uploaded()
{
Storage::fake('photos');

$response = $this->json('POST', '/photos', [
UploadedFile::fake()->image('photo1.jpg'),
UploadedFile::fake()->image('photo2.jpg')
]);

// Assert one or more files were stored...
Storage::disk('photos')->assertExists('photo1.jpg');
Storage::disk('photos')->assertExists(['photo1.jpg', 'photo2.jpg']);

// Assert one or more files were not stored...
Storage::disk('photos')->assertMissing('missing.jpg');
Storage::disk('photos')->assertMissing(['missing.jpg', 'non-existing.jpg']);

// Assert that a given directory is empty...
Storage::disk('photos')->assertDirectoryEmpty('/wallpapers');
}
}

最新更新