1

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

The result of phpunit is: phpunit result

But, when I check the code coverage result, the line inside the if statement on routes.php file is not executed as shown below.

Code coverage result

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

1

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.