如何使用 laravel 和 phpunit 测试文件上传?

2022-01-25 00:00:00 php laravel phpunit

我正在尝试在我的 laravel 控制器上运行此功能测试.我想测试图像处理,但这样做我想伪造图像上传.我该怎么做呢?我在网上找到了一些例子,但似乎没有一个适合我.这是我所拥有的:

I'm trying to run this functional test on my laravel controller. I would like to test image processing, but to do so I want to fake image uploading. How do I do this? I found a few examples online but none seem to work for me. Here's what I have:

public function testResizeMethod()
{
    $this->prepareCleanDB();

    $this->_createAccessableCompany();

    $local_file = __DIR__ . '/test-files/large-avatar.jpg';

    $uploadedFile = new SymfonyComponentHttpFoundationFileUploadedFile(
        $local_file,
        'large-avatar.jpg',
        'image/jpeg',
        null,
        null,
        true
    );


    $values =  array(
        'company_id' => $this->company->id
    );

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

    $readable_response = $this->getReadableResponseObject($response);
}

但是控制器没有通过这个检查:

But the controller doesn't get passed this check:

elseif (!Input::hasFile('file'))
{
    return Response::error('No file uploaded');
}

所以不知何故文件没有正确传递.我该怎么办?

So somehow the file isn't passed correctly. How do I go about this?

推荐答案

CrawlerTrait.html#method_action 的文档 内容如下:

参数
字符串 $method
字符串 $action
数组 $wildcards
数组 $parameters
数组 $cookies
数组 $files
数组 $server
字符串$内容

Parameters
string $method
string $action
array $wildcards
array $parameters
array $cookies
array $files
array $server
string $content

所以我认为正确的调用应该是

So I assume the correct call should be

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

除非它需要非空通配符和 cookie.

unless it requires non-empty wildcards and cookies.

相关文章