nafeeur10's avatar

Writing Unit Test for CSV file upload in Laravel

I have an CSV file with two columns:

id     amount
-------------
1      1000
2      1500
3      5800

Now I want to write Unit Test for this. After uploading this file which steps I need to follow to write proper test case?

0 likes
1 reply
tisuchi's avatar

@nafeeur10 Ideally it should be-


/** @test */
public function it_uploads_csv_files()
{
	// Arrange
	Storage::fake('csvfile');
        $file = UploadedFile::fake()->create('foo.csv');

	// Act
        $response = $this->post('/avatar', [
		'file' => $file,
        ]);

	// Assert
        Storage::disk('csvfile')->assertExists($file->hashName());

	# Check if you have any DB entry against that
	$this->assertDatabaseHas('table_name', [
		'file' => $file->name	// I assume you store file name in the table.
		// You can check more stuff here.
	]);
}

Ref: https://laravel.com/docs/9.x/http-tests#testing-file-uploads

1 like

Please or to participate in this conversation.