0
我想用有效格式测试我的端点。例如,我有/api/token
(POST),它将返回api标记。Laravel测试 - 如何验证JSON响应中的每个字段
在我的情况下,此端点将返回“标记”字符串和“消息”字段。因此,我想检查这两个字段是否存在有效格式。目前我正在使用Laravel Validator。
例JSON输出:
{
"message": "login successful",
"token": "d4zmendnd69u6h..."
}
Test类(ApiTokenTest.php)。
class ApiTokenTest extends TestCase
{
protected $validFormBody = [
'os_type' => 'android',
'device_id' => '0000-AAAA-CCCC-XXXX',
'os_version' => '5.1',
'apps_version' => '1.0',
];
public function testSucessResponseFormat()
{
$response = $this->json('post', '/api/token', $this->validFormBody);
$validator = Validator::make(json_decode($response->getContent(), true), [
'token' => 'required|size:100', // token length should be 100 chars
'message' => 'required',
]);
if ($validator->fails()) {
$this->assertTrue(false);
}
else {
$this->assertTrue(true);
}
}
}
这里的问题是失败的消息是不是真的有帮助,特别是如果我有超过1个字段的格式无效,应我断言一个接一个? (见失败案例下的phpunit
输出)。我应该使用什么来验证每个字段的格式? 在此先感谢。
There was 1 failure:
1) Tests\Feature\ApiTokenTest::testSucessResponseFormat
Failed asserting that false is true.
感谢您的想法。我用'fwrite(STDERR,print_r($ validator-> errors() - > all(),true));'来正确显示输出 – xmhafiz