【发布时间】:2020-12-18 16:21:03
【问题描述】:
在使用单元测试测试 API 时,是否可以从错误包中打印消息?是的,它已经显示了异常,但没有具体说明错误的具体内容和验证方式。
为了清楚起见,请看一下:
Tests: 1 failed, 23 passed, 3 pending
Illuminate\Validation\ValidationException
The given data was invalid
我所期待的:
Tests: 1 failed, 23 passed, 3 pending
Illuminate\Validation\ValidationException
The given data was invalid, [
'errors' => [all the validation errors listed here]
]
更新
已经试过了,但是不行:
// inside setUp method
$this->withoutExceptionHandling();
// inside test method
$this->postJson($uri, $this->newUser)
// ->dumpSession()
// ->dumpHeader()
->dump();
另外,请看一下我的脚本:
public function testCustomerCanStoreNewUser()
{
$this->actingAs($this->customer, 'api');
$uri = route('users.store');
$this->postJson($uri, $this->newUser)
->dumpSession()
->dumpHeaders()
->dump()
->assertCreated()
->assertJsonStructure(['success', 'data']);
$this->assertDatabaseHas('users', $this->newUser);
}
【问题讨论】:
-
当您执行
postJson时,响应对象应包含验证结果,除非您进行手动验证。 -
对不起,我不明白。我已经更新了我的问题,请看一下。
-
尝试删除
withoutExceptionHandling部分以获得正确的验证异常响应。 -
通过删除
withoutExceptionHandling,它只显示状态码422。我们知道这是一个验证错误,但它并没有告诉我们错误在哪个字段。 -
响应内容应包含验证错误
标签: laravel laravel-7 laravel-testing