Reputation: 1172
I want to do some unit testing with file upload on Laravel 5.2.
Here is how I do it refer to this answer:
/** app/Http/routes.php **/
Route::post('upload', function() {
$fileExists = false;
if ($_FILES['images']) {
$fileExists = true;
}
return ['result' => $fileExists];
});
/** tests/ExampleTest.php **/
public function testUploadFile()
{
$file = new \Symfony\Component\HttpFoundation\File\UploadedFile(
base_path() . '/tests/files/profile.png', 'profile.png');
$response = $this->call('POST', 'upload',
[
'firstname' => 'firstname',
'lastname' => 'lastname',
'promotion' => '2016',
'isCoop' => 1
],
[
'images' => [$file]
]
);
}
But, when I check the code coverage result, the line inside the if statement on routes.php file is not executed as shown below.
It seems the uploaded file is not inserted into $_FILES
variable, so it detected as empty.
Any idea how to fix it..? Thanks.
Notes: I used Larave for create an API Service, so I did not used form to upload the file
Upvotes: 1
Views: 1057
Reputation: 932
I think you should write:
[
'images' => $file
]
Instead of
[
'images' => [$file]
]
Also, you should use Illuminate\Http\UploadedFile instead of Symfony\Component\HttpFoundation\File\UploadedFile after 5.2.15 see Laravel 5.2 Mocked file upload unit test fails
Upvotes: 0
Reputation: 171
After laravel 5.2.15 this is happening because you are using
Symfony\Component\HttpFoundation\File\UploadedFile
instead of
Illuminate\Http\UploadedFile
And file is never sent to a controller.
Upvotes: 1