0

我只是将应用程序从 laravel 5.3 移动到 5.4。在我的 API 测试中的 laravel 5.3 中,我可以验证响应中的每条记录都具有以下代码的属性:

$this->json('get', '/api/course-types')
        ->seeJsonStructure([
            '*' => ['id', 'aaa', 'bbb', 'ccc', 'ddd']
        ]);

我如何使用 laravel 5.4 做同样的事情?

Illuminate/Foundation/Testing/TestResponse中没有这样的方法

4

3 回答 3

1

相信你正在寻找assertJson()assertExactJson()

文档

assertJson 方法将给定数组转换为 JSON,然后验证 JSON 片段是否出现在应用程序返回的整个 JSON 响应中的任何位置。因此,如果 JSON 响应中有其他属性,只要存在给定的片段,此测试仍将通过。

及相关代码:

$response = $this->json('POST', '/user', ['name' => 'Sally']);

$response
    ->assertStatus(200)
    ->assertJson([
        'created' => true,
    ]);

assertExactJson()将寻找完全匹配,而assertJson()只是验证响应中参数的存在。希望能帮助到你!

于 2017-01-26T16:51:39.917 回答
1

browserkit 测试功能被 Laravel Dusk 取代。原始功能已移至其自己的包:laravel/browser-kit-testing

这个包为 Laravel 5.4 上的 Laravel 5.3 风格的“BrowserKit”测试提供了向后兼容层。

您将需要遵循该软件包上的安装和使用说明,然后您现有的测试将像在 5.3 中一样工作。

于 2017-01-26T17:22:15.133 回答
0

我也用seeJsonStructure()了很多,所以我拼凑了一个小替代品放在我自己的TestCase. 希望它对某人有帮助,或者有人可以建议我更好的解决方案:

添加到我的TestCase

public function seeJsonStructure(TestResponse $response = null, array $structure = null, $responseData = null)
{
    if ($response && !$responseData) {
        $responseData = $response->decodeResponseJson();
    }
    if (is_null($structure)) {
        return $response->assertJson($responseData);
    }
    foreach ($structure as $key => $value) {
        if (is_array($value) && $key === '*') {
            $this->assertInternalType('array', $responseData);
            foreach ($responseData as $responseDataItem) {
                $this->seeJsonStructure(null, $structure['*'], $responseDataItem);
            }
        } elseif (is_array($value)) {
            $this->assertArrayHasKey($key, $responseData);
            $this->seeJsonStructure(null, $structure[$key], $responseData[$key]);
        } else {
            $this->assertArrayHasKey($value, $responseData);
        }
    }
    return $this;
}

然后,我必须更新我的测试,所以我在调用此方法时将响应作为第一个参数传递。示例SomeTest

$response = $this->json('POST', $url, [
    'id' => $user->id
]);

$this->seeJsonStructure($response, [
    'id', 'first_name', 'last_name', 'email'
]);

原来的 Laravel 方法是:https ://github.com/laravel/browser-kit-testing/blob/85f9a14a63bf5a287740002fcbc4352587f8a113/src/Concerns/MakesHttpRequests.php#L348

于 2017-02-02T07:06:01.120 回答