Unai Susperregi
Unai Susperregi

Reputation: 414

How to set file post properly PhpUnit

I'm trying to set a test to upload a file. In the controller I need to check if everyting is ok (form validation).

The problem is the response gives me an error $request->dataFile->getClientOriginalExtension() , (vendor/symfony/http-foundation/File/UploadedFile.php)

Looks like the dataFile, or request or.... I dont know how to set it.

/** 
        @test 
        @group formPostFile
*/
public function formPostFile()
{
    $test_file_path  = base_path().'/httpdocs/test/Excel.xlsx';
    $this->assertTrue(file_exists($test_file_path), $test_file_path.' Test file does not exist');
    $_FILE = [
        'filename' => [
            'name'     => $test_file_path,
            'type'     => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
            'size'     => 10336,
            'tmp_name' => $test_file_path,
            'error'    => 0
        ]
    ];
    $data = [
        'id' => '2',
        'dataFile' => $_FILE
    ];
    $response = $this->post('/excel', $data);
    dd($response->getContent());

}

Upvotes: 1

Views: 75

Answers (1)

mrhn
mrhn

Reputation: 18976

Utilise the Symfony/Illuminate class UploadedFile

$file = new UploadedFile(
    $test_file_path, 
    $test_file_path,
    filesize($test_file_path),
    'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
    null,
    true
);

LastParameter is testMode and should be true, i believe this will work out in your code, utilise it in a similar fashion as the array you already have like so.

$data = [
    'id' => '2',
    'dataFile' => $file
];

Upvotes: 1

Related Questions