php - 集成测试文件上传
问题描述
我目前正在开发一个具有某些表单功能的 MVC 网站。作为表单的一部分,用户可以选择上传文件。我已经为此编写了代码并且它运行良好,但我的问题来自于尝试编写自动化测试以确保我不会在未来的重构中破坏任何东西。
我已阅读有关文件上传的 laravel 文档并尝试复制此文件,但在断言文件存在时失败。该表格是可选的,但有一些数据需要与它一起发送。
测试文件
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.
我不太确定我要去哪里,所以任何提示都会很棒。
谢谢
解决方案
您在 POST 数据中将文件名作为字符串传递,但这是不正确的。您需要将文件本身发布到测试框架。您可以使用该call
方法执行此操作。第 5 个参数用于发布的文件。
$this->call('POST', route('route.to.test'), $params, [], compact('file'))
推荐阅读
- django - 如何从 DJANGO REST FRAMEWOK 中的序列化模型创建 excel 以供使用(下载)
- rest - 使用 databricks Resr API 运行 spark 作业
- java - 是否可以使用 OAuth2 创建基于角色的应用程序?
- python - 如何将矩阵中每一列的伪逆(来自SVD)乘以Python中的另一个向量
- javascript - 为什么在刷新网页后,转录记录器/webBot 会存储先前对话的活动?
- javascript - 运行特快路线
- tcl - 错误的窗口路径名“.snd”
- java - 将数据加载到java中的下拉列表?
- python - 从 pandas 数据框生成变更日志
- python - Scrapy:如何使用`python将产量输出保存到json中
`?