我目前正在为我的API编写一些测试,我很想知道是否有更好的方法来处理这个问题,因为我觉得这是一种"技巧"的做事方式。
下面的代码示例:
public function testListingOfAllUsers()
{
$users = $this->createUsers();
$client = $this->createClient();
$client->request("GET", "/users/");
$response = $client->getResponse();
$content = $response->getContent();
$decodedContent = json_decode($content);
$this->assertTrue($response->isOk());
$this->assertInternalType("array", $decodedContent->data);
$this->assertCount(count($users), $decodedContent->data);
foreach ($decodedContent->data as $data) {
$this->assertObjectHasAttribute("attributes", $data);
$this->assertEquals("users", $data->type);
}
}
我想知道是否有更好的方法来测试我的API是否与JSON API规范匹配。启发我!我很确定PHPUnit不是我的答案。
首先,我不认为像现在这样用程序断言某个JSON结构本身就是一种糟糕的做法。然而,我确实同意,它可能会在某个时候变得麻烦,并且可以更有效地解决。
不久前,我也遇到了同样的问题,最终编写了一个新的Composer包(helmich/phpunit-json-assert
,可作为开源),该包使用JSON模式和JSONPath表达式来验证给定JSON文档的结构。
使用JSON模式,您的示例测试用例可以编写如下:
public function testListingOfAllUsers()
{
$users = $this->createUsers();
$client = $this->createClient();
$client->request("GET", "/users/");
$response = $client->getResponse();
$content = $response->getContent();
$decodedContent = json_decode($content);
$this->assertTrue($response->isOk());
$this->assertJsonDocumentMatchesSchema($decodedContent, [
'type' => 'array',
'items' => [
'type' => 'object',
'required' => ['attributes', 'type'],
'properties' => [
'attributes' => ['type' => 'object'],
'type' => ['type' => 'string', 'enum' => ['user']]
]
]
]);
}
尽管(关于代码行)有点冗长,但我已经开始欣赏这个用例的JSON模式,因为它是一个广泛采用的标准,(imho)更容易阅读assert*
语句墙。您还可以将单元测试中的模式定义提取到单独的文件中,并用它们做其他事情;例如自动生成文档(Swagger也使用JSON模式的子集)或运行时验证。