如何将文件注入http请求

how to inject a file into http request

我有一个测试用例:

$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')) 时,它 return 为空。 那么,我如何将文件请求到我的控制器中。 请帮忙

如本文所述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');

您可以像这样使用 UploadFile:

$fileName= 'file.png';
$filePath=sys_get_temp_dir().'/'.$fileName;
$mimeTypeFile=mime_content_type($filePath);
$file=new UploadedFile($filePath, $fileName, $mimeTypeFile, filesize('$filePath'), null, true)
$response = $this->postJson('api/unit/'.$unit->id.'/import',['file' =>$file]);
$response->assertJsonFragment(['a'=>'b']);

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