Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Dhaval_patel's avatar

File uploads error with Unit testing

Hey guys, I am having an issue with my unit testing Can anyone help? Here is my TestController inside tests/Unit


namespace Tests\Unit;

use Tests\TestCase;
use Illuminate\Foundation\Testing\WithFaker;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Storage;
use Illuminate\Http\UploadedFile;

class ExcelTest extends TestCase
{
    /**
     * A basic test example.
     *
     * @return void
     */
    public function testExample()
    {
        // Fake any disk here
        Storage::fake('local');

        // Create file
        file_put_contents(storage_path().'/app/xls/file.xls', "MC,What is 2+2?,4\n");

        $response = $this->postJson('/excel-demo', [
            'file' => new UploadedFile(storage_path().'/app/xls/file.xls','file.xls', null, null, null, true),
        ])->assertStatus(200);
        /*$response = $this->json('POST', '/excel-demo', [
            'file' => UploadedFile::fake()->create(storage_path().'/app/xls/file.xls')
        ]);*/
        Storage::disk('local')->assertExists('file.xls');

    }
}

Here is my controller ExcelController


namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;

class ExcelController extends Controller
{
    public function Excel(Request $request)
    {
        $file = $request->file('file');

        Storage::disk('local')->putFileAs('xls', $file, $file->getClientOriginalName());

        \Excel::load(storage_path().'/app/xls/'.$file->getClientOriginalName(), function($file) {

        })->convert('csv');
        return response([
            'message' => 'uploaded'
        ], 200);
    }
}

I am getting this error while running this test


Runtime:       PHP 7.1.11
Configuration: C:\xampp\htdocs\Application\phpunit.xml

F                                                                   1 / 1 (100%)

Time: 1.43 seconds, Memory: 16.00MB

There was 1 failure:

1) Tests\Unit\ExcelTest::testExample
Expected status code 200 but received 500.
Failed asserting that false is true.

FAILURES!
Tests: 1, Assertions: 1, Failures: 1.```
0 likes
4 replies
bobbybouwmann's avatar

Your code is giving a 500 back instead of 200 error. Somehow you have an error in your code. Have you tried manually perform this task? It should give you the same exception.

You can probably see in your logs what the error was.

You can also enable exception handling in your test to actually see the exception in your test by adding this add the top of your test

public function testSomething()
{
    $this->withoutExceptionHandling();

    // Your test here

    // Your assertion here
}

Please or to participate in this conversation.