如何将文件注入http请求

时间:2018-10-12 08:55:18

标签: laravel unit-testing phpunit laravel-testing

我有一个测试用例:

$response = $this->postJson('api/unit/'.$unit->id.'/import',['file' =>Storage::get('file/file.xlsx')]);
    $response->assertJsonFragment(['a'=>'b']);

我的控制器:

public function import(Request $request, Unit $unit)
{

    $this->validate($request, [
        'file' => 'file|required_without:rows',
        'rows' => 'array|required_without:file',
        'dry_run' => 'boolean',
    ]);
    if ($request->has('rows')) {
        //
    } else {
        $results = $request->file('file');
    }

    return "ok";
}

但是我认为我的测试用例是错误的,因为当我在控制器中dd($ reuqest-> file('file'))时,它返回null。 所以,我怎样才能请求文件到我的控制器。 请帮助

2 个答案:

答案 0 :(得分:1)

您可以像这样使用UploadFile:

select * from
(
select gpsDateTime as Timee,long,lat, fleetNumber,row_number() over(partition by fleetNumber order by gpsDateTime desc ) as rn
from GPS 
Where cast(gpsDateTime as Date) =  '2018-10-03' 
)X where rn=1

其中null为上传错误常数,true为测试模式 有关Symfony UploadedFile的更多详细信息,请阅读this

答案 1 :(得分:0)

如本https://laravel.com/docs/5.4/http-tests#testing-file-uploads中所述。

尝试类似这样的方法。导入使用Illuminate \ Http \ UploadedFile;

UploadedFile::fake()->create('file.xlsx', $size);
Storage::disk('file')->assertExists('file.xlsx');