Praditha
Praditha

Reputation: 1172

How to do Unit Testing + code-coverage with file upload in Laravel 5.2

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

Upvotes: 1

Views: 1057

Answers (2)

Ahmed Ismail
Ahmed Ismail

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

staskus
staskus

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

Related Questions