laravel - Laravel Phpunit 测试一个请求,根据请求给出输出
问题描述
我还是 laravel 的新手,我有一个简单的应用程序,所以我有一个路由,可以根据我的控制器中的请求存储数据。
public funtion store(Request $request, $id){
if ($request->has('work_experiences')) {
WorkExperience::create([
'user_id' => $user->id,
'position' => $request->work_experiences['position'],
'company' => $request->work_experiences['company'],
'start_date' => $request->work_experiences['start_date'],
'end_date' => $request->work_experiences['end_date'],
]);
}
if ($request->has('education')) {
Education::create([
'user_id' => $user->id,
'degree' => $request->education['degree'],
'university' => $request->education['university'],
'start_date' => $request->education['start_date'],
'end_date' => $request->education['end_date'],
]);
}
if ($request->has('job_interests')) {
JobInterest::create([
'user_id' => $user->id,
'job_position' => $request->job_interests['position'],
]);
}}
}
在我的测试中
public function test_authenticated_user_can_edit_education_profile()
{
$this->withoutExceptionHandling();
$user = User::factory()->create();
$this->actingAs($user);
$response = $this->post('/candidate' . '/' . $user->id, [
'user_id' => $user->id,
'position' => 'position',
'company' => 'company',
'start_date' => Carbon::now(),
'end_date' => Carbon::now(),
]);
$this->assertCount(1, WorkExperience::all());
}
当我运行测试时,assertCount 似乎失败了,因为响应不起作用/将数据插入数据库。我在哪里做错了?
解决方案
嗯,测试是对的。
它应该会失败,因为您的请求数据中没有work_experiences
密钥。
测试请求应如下所示:
$response = $this->post('/candidate' . '/' . $user->id, [
'work_experiences' => [
'user_id' => $user->id,
'position' => 'position',
'company' => 'company',
'start_date' => Carbon::now(),
'end_date' => Carbon::now(),
]
]);
所以你的数据应该在一个返回 true 并执行语句的work_experiences
键下。$request->has('work_experiences')
WorkExperience::create()
目前,您的端点只允许创建单一的“工作体验”。看到您已将其命名,work_experiences
我假设您想传入“工作经验”的数组/集合-但这不适用于当前的实现;你将不得不循环它们 - 像这样:
if ($request->has('work_experiences')) {
foreach ($request->input('work_experiences') as $experience) {
WorkExperience::create([
'user_id' => $request->user()->id,
'position' => $experience['position'],
'company' => $experience['company'],
'start_date' => $experience['start_date'],
'end_date' => $experience['end_date'],
]);
}
}
然后你的测试应该是这样的:
$response = $this->post('/candidate' . '/' . $user->id, [
'work_experiences' => [
[
'user_id' => $user->id,
'position' => 'position',
'company' => 'company',
'start_date' => Carbon::now(),
'end_date' => Carbon::now(),
],
// more "work experiences"
]
]);
推荐阅读
- image - Xamarin - 如何显示来自 Object 属性的图像
- excel - 在具有相同工作簿的特定工作表的公式中使用的工作表的列表名称
- apache - Apache Isis 中的可自定义表列
- python - Python:RuntimeWarning:在正方形中遇到溢出
- excel - Excel VBA 将数据循环到电子邮件正文中
- laravel - 删除 Eloquent 中的第二层归属感
- javascript - 动态创建具有动态 onclick 功能的 div
- c - 在 C 中,如何打印出一个字符数组然后将其清空?
- android - Android Jetpack navigationUI,如何传递数据以查看寻呼机片段
- java - org/hibernate/service/ServiceRegistry:NoClassDefFoundError