如何在 Lumen 上对 GraphQL 响应进行单元测试?

How to unit test GraphQL responses on Lumen?

我正在尝试测试我用 Lumen (PHP) 构建的 API,但我卡在 unit test 我的 GraphQL 响应上。

这是我试过的:

class MovieQueryTest extends Tests\GraphQLTestCase
{
    use DatabaseMigrations;

    public function testCanSearch()
    {
        Movie::create([
            'name' => 'Fast & Furious 8',
            'alias' => 'Fast and Furious 8',
            'year' => 2016
        ]);

        $response = $this->post('/graphql/v1', [
            'query' => '{movies(search: "Fast & Furious"){data{name}}}'
        ]);

        $response->seeJson([
            'data' => [
                'movies' => [
                    'data' => [
                        'name' => 'Fast & Furious 8'
                    ]
                ]
            ]
        ]);
    }
}

这是我得到的:

PHPUnit 7.5.6 by Sebastian Bergmann and contributors.

F..... 6 / 6 (100%)

Time: 690 ms, Memory: 24.00 MB

There was 1 failure:

1) MovieQueryTest::testCanSearch Unable to find JSON fragment ["data":{"movies":{"data":{"name":"Fast & Furious"}}}] within [{"data":{"movies":{"data":[]}}}]. Failed asserting that false is true.

问题是我的数据结构与 JSON's 结构不匹配。虽然我的数据在 Array 中,但 JSON 的数据在 Object 中,但我不知道如何使其匹配:

如何使我的数据结构与 JSON 的数据结构匹配,或者有更好的方法在 Lumen 上对 GraphQL 响应进行单元测试?

您需要将 'name' => 'Fast & Furious 8' 包装在它自己的数组中,例如:

以下:

$array = [
    'data' => [
        'movies' => [
            'data' => [
                ['name' => 'Fast & Furious 8']
            ]
        ]
    ]
];

应该输出:

{"data":{"movies":{"data":[{"name":"Fast & Furious 8"}]}}}