Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test in PHPUnit; a CSV File Upload using an API written in Laravel?

I would like to upload a CSV file via a Laravel API then test the upload with PHPUnit.

What would my store() function in the Controller and testCreate() function basically look like.

This is what I got so far:

<?php

use Illuminate\Foundation\Testing\DatabaseTransactions;
use Illuminate\Foundation\Testing\WithoutMiddleware;

class ProspectListControllerTest extends TestCase
{

use WithoutMiddleware, DatabaseTransactions;

public function testCreate()
{

    $file = new Symfony\Component\HttpFoundation\File\UploadedFile(storage_path('/crm/data/test-file.csv'), 'test-file.csv', 'text/plain', 446, null, true);

    $this->call('POST', '/api/lists-imports/', [], [], ['csv_file' => $file]);
    $this->dump()->assertResponseOk();
  }
}

and the controller method looks like:

<?php

namespace App\Http\Controllers;

use App\ListImport;
use Illuminate\Http\Request;

class ListImportController extends Controller
{
public $model = ListImport::class;

public function store(Request $request, ListImport $importList)
{
    $request->file('importFile')->move(public_path('storage.crm.data'), $request->file('importFile')->getClientOriginalName());

    $importList->importFile = public_path('storage.crm.data') . '/' . $request->file('importFile')->getClientOriginalName();

    $importList->save();

}
}

Any help will be appreciated :)

like image 981
Devin Norgarb Avatar asked Jun 02 '16 06:06

Devin Norgarb


1 Answers

Here's an example of my feature test Laravel 6 and higher ('uploads' is my storage driver):

    use Illuminate\Http\UploadedFile;

    Storage::fake('uploads');

    $header = 'Header 1,Header 2,Header 3';
    $row1 = 'value 1,value 2,value 3';
    $row2 = 'value 1,value 2,value 3';

    $content = implode("\n", [$header, $row1, $row2]);

    $inputs = [
        'csv_file' =>
            UploadedFile::
                fake()->
                createWithContent(
                    'test.csv',
                    $content
                )
    ];


    $response = $this->postJson(
        'file-upload',
        $inputs

    );

    $response->assertOk();
like image 122
Matt Holmes Avatar answered Nov 05 '22 06:11

Matt Holmes