【发布时间】:2017-12-10 20:34:45
【问题描述】:
我想用有效的格式测试我的端点。例如,我有 /api/token (POST),它将返回 api 令牌。
在我的例子中,这个端点将返回“token”字符串和“message”字段。因此,我想检查这两个字段是否以有效格式存在。目前我正在使用Laravel Validator。
示例 json 输出:
{
"message": "login successful",
"token": "d4zmendnd69u6h..."
}
测试类(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.
【问题讨论】:
标签: php laravel unit-testing