【问题标题】:Integration Testing JSON API Response集成测试 JSON API 响应
【发布时间】:2016-04-15 10:17:30
【问题描述】:

我目前正在为我的 API 编写一些测试,我很想知道是否有更好的方法来处理这个问题,因为我觉得这是“hacky”的做事方式。

下面的代码示例:

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 不是我的答案。

【问题讨论】:

    标签: php json phpunit integration-testing silex


    【解决方案1】:

    首先,我不认为像您现在所做的那样以编程方式断言某个 JSON 结构本身就是不好的做法。但是,我确实同意它在某些时候可能会变得很麻烦并且可以更有效地解决。

    不久前我遇到了同样的问题,最后编写了一个新的 Composer 包(helmich/phpunit-json-assert,即available as open source),它使用JSON schemataJSONPath expressions 来验证给定 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 模式,因为它是一个被广泛采用的标准并且(恕我直言)更容易阅读 @ 墙987654327@ 声明。您还可以将单元测试中的模式定义提取到单独的文件中,然后用它们做其他事情;例如自动生成文档(Swagger 也使用 JSON 模式的子集)或运行时验证。

    【讨论】:

    • 非常感谢。这周我一定要看看你的包裹。我觉得我在做正确的事情,只是觉得它可以更整洁。你的回答肯定有帮助!再次感谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-18
    • 2019-04-27
    • 2023-02-07
    • 2014-02-15
    • 1970-01-01
    • 2014-10-01
    相关资源
    最近更新 更多