我目前正在开发具有某些表单功能的MVC网站。作为表单的一部分,用户可以选择上传文件。我已经为此编写了代码,并且运行良好,但是我的问题出在试图编写自动化测试以确保将来的重构不会破坏任何东西。
我已经阅读了laravel文档中的文件上传信息,并尝试复制此文件,但是断言文件存在时失败。该表格是可选的,但需要随其发送一些数据。
TestFile
public function testDirect_FormPassesWithFile()
{
Storage::fake('local');
$file = UploadedFile::fake()->create('document.pdf');
$response = $this->post('/direct', $this->data());
$response->assertSessionHasNoErrors();
Storage::disk('local')->assertExists($file->hashName());
$response->assertStatus(302);
$this->assertCount(1, QuickQuote::all());
}
private function data()
{
return [
'name' => $this->faker->name,
'email' => $this->faker->email,
'phone' =>'07718285557',
'risk' => $this->faker->address,
'rebuild' => $this->faker->numberBetween($min = 500000, $max = 1000000),
'startdate' => '2019-09-01',
'currentpremium' => $this->faker->numberBetween($min = 100, $max = 1000),
'file' => 'document.pdf',
'_token' => csrf_token()
];
}
控制器
public function store(StoreQuickQuote $request)
{
$validated = $request->validated();
//Code entered if there are any files uploaded
if ($request->file('file')) {
//loop through each file and store, saving path to an array
$files = array();
foreach($request->file('file') as $file) {
$path = $file->store('uploads');
array_push($files, $path);
}
//Turn the array into json and then insert into the validated data
$filenames = json_encode($files);
$merged = array_merge($validated, ['file' => $filenames]);
$quick_quote = QuickQuote::create($merged);
}
//No files so just store
$quick_quote = QuickQuote::create($validated);
return redirect('/direct')->with('success', 'Thanks! We\'ll Be In Touch.');
}
验证请求
public function rules()
{
return [
'name' => 'required',
'email' => 'required|email',
'phone' => 'required',
'risk' => 'required',
'rebuild' => 'required',
'startdate' => 'required',
'currentpremium' => 'present',
'file' => 'nullable'
];
}
表单输入
<input type="file" id="file" name="file[]" multiple>
我的输出始终是
There was 1 failure:
1) Tests\Feature\DirectTest::testDirect_FormPassesWithFile
Unable to find a file at path [mJ4jQ2hmxW6uMMPEneUVS6O4bZziuuTT5kq2NFVS.pdf].
Failed asserting that false is true.
我不太确定要去哪里,所以任何提示都很棒。
谢谢
答案 0 :(得分:0)
您正在将文件名作为字符串传递到POST数据中,但这是不正确的。您需要将文件本身发布到测试框架。您可以使用call
方法执行此操作。第5个参数用于发布的文件。
$this->call('POST', route('route.to.test'), $params, [], compact('file'))