Laravel测试,获取JSON内容

rap*_*2-h 37 phpunit laravel laravel-5

在Laravel的单元测试中,我可以像这样测试一个JSON API:

$this->post('/user', ['name' => 'Sally'])
    ->seeJson([
        'created' => true,
    ]);
Run Code Online (Sandbox Code Playgroud)

但是,如果我想使用响应怎么办?如何使用$this->post()?获取JSON响应(作为数组)?

Jan*_*pák 54

获取内容的正确方法是:

$content = $this->get('/v1/users/1')->decodeResponseJson();
Run Code Online (Sandbox Code Playgroud)

  • 我同意。在 5.4 中工作。 (3认同)

Mik*_*Lin 33

目前在5.3这是工作......

$content = $this->get('/v1/users/1')->response->getContent();

它确实打破了链条,但是因为response返回响应而不是测试运行器.所以,你应该在获取响应之前做出可链接的断言,就像这样......

$content = $this->get('/v1/users/1')->seeStatusCode(200)->response->getContent();

  • 在 Laravel 7 中使用“decodeResponseJson”是正确的方法。这将返回字符串。 (4认同)

cma*_*mac 10

我喜欢在使用json时使用json方法,而不是-> get()

$data = $this->json('GET', $url)->seeStatusCode(200)->decodeResponseJson();
Run Code Online (Sandbox Code Playgroud)


Dan*_*iel 7

我遇到了类似的问题,无法使用内置的$ this-> get()方法获取$ this-> getResponse() - > getContent().我尝试了几种变化但没有成功.

相反,我不得不更改调用以返回完整的http响应并从中获取内容.

// Original (not working)
$content = $this->get('/v1/users/1')->getContent();

// New (working)
$content = $this->call('GET', '/v1/users/1')->getContent();
Run Code Online (Sandbox Code Playgroud)


Mwt*_*eex 7

简单的方法:

$this->getJson('api/threads')->content()
Run Code Online (Sandbox Code Playgroud)

  • 这里使用 json() 而不是 content() 来对响应数据进行 json 解码 (2认同)

小智 7

在 Laravel 6 中,这对我有用。在 POST 请求创建实体后,我返回了一个自动生成的字段(余额)。响应在结构中{"attributes":{"balance":12345}}

$response = $this->postJson('api/v1/authors', [
    'firstName' => 'John',
    'lastName' => 'Doe',
])->assertStatus(201);

$balance = $response->decodeResponseJson()['attributes']['balance'];
Run Code Online (Sandbox Code Playgroud)

decodeResponseJson将选择响应并将其转换为数组以进行操作。使用getContent()返回 json,您必须使用json_decode返回的数据将其转换为数组。


小智 6

找到了更好的方法:

$response = $this->json('POST', '/order', $data);
$responseData = $response->getOriginalContent(); // saves the response as an array
$responseData['value']  // you can now access the array values

Run Code Online (Sandbox Code Playgroud)

此方法以数组形式返回响应 json。


Sha*_*man 5

只是想分享,我也用过同样的东西$this->json()

$response = $this->json('POST', '/order', $data)->response->getContent();
Run Code Online (Sandbox Code Playgroud)

但我又添加了一行来使用 json 响应和解码,否则decodeResponseJson()对我不起作用。

$json = json_decode($response);
Run Code Online (Sandbox Code Playgroud)