Jasper Kennis Jasper Kennis -4 years ago 115
PHP Question

How to test file upload with laravel and phpunit?

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 Symfony\Component\HttpFoundation\File\UploadedFile(
$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?




Update

Based on max.lanin's suggestin, I also tried:

public function setUp()
{
// Tried with parent::setUp() here and at the end
// parent::setUp();
$local_file = __DIR__ . '/test-files/large-avatar.jpg';

print($local_file);

$_FILES = array(
'file' => array (
'tmp_name' => $local_file,
'name' => 'large-avatar.jpg',
'type' => 'image/jpeg',
'size' => 335057,
'error' => 0,
),
'image' => array (
'tmp_name' => $local_file,
'name' => 'large-avatar.jpg',
'type' => 'image/jpeg',
'size' => 335057,
'error' => 0,
),
);

parent::setUp();
}


but without succes. The file used exists and the size is correct.

Answer Source

Docs for CrawlerTrait.html#method_action reads:

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

unless it requires non-empty wildcards and cookies.

As a side note, it is by no means a unit test.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download