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)
Mik*_*Lin 33
目前在5.3这是工作......
$content = $this->get('/v1/users/1')->response->getContent()
;
它确实打破了链条,但是因为response
返回响应而不是测试运行器.所以,你应该在获取响应之前做出可链接的断言,就像这样......
$content = $this->get('/v1/users/1')->seeStatusCode(200)->response->getContent()
;
cma*_*mac 10
我喜欢在使用json时使用json方法,而不是-> get()
$data = $this->json('GET', $url)->seeStatusCode(200)->decodeResponseJson();
Run Code Online (Sandbox Code Playgroud)
我遇到了类似的问题,无法使用内置的$ 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)
简单的方法:
$this->getJson('api/threads')->content()
Run Code Online (Sandbox Code Playgroud)
小智 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。
只是想分享,我也用过同样的东西$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)