我正在使用Laravel,我的代码就是这样
$this->actingAs($user)
->json('post', '/graphql/admin', ['query' => $query])
->assertStatus(200)
->assertJsonStructure($expected);
如果此测试失败,我想打印变量$query
。
我的理想做法是在代码末尾添加一些类似的内容:
if ($this->isFail()) {
echo $query;
}
答案 0 :(得分:0)
在文件TestCase.php
中添加此功能
// tests/TestCase.php
public function assertJsonStructure(
string $url,
array $params,
array $expected
) {
$response = $this->json('post', $url, $params);
try {
$response->assertStatus(200)->assertJsonStructure($expected);
} catch (\Exception $ex) {
$this->printDie($params, $expected, $ex, $response);
}
}
此功能:
// tests/TestCase.php
private function printDie($params, $expected, \Exception $ex, $response, $user_id = null)
{
$content = substr($response->getContent(), 0, 1500);
$trace = debug_backtrace();
$error = [
'class' => static::class.'::'.$trace[2]['function'],
'params' => $params,
'expected' => $expected,
'user' => $user_id,
'error' => $ex->toString(),
'content' => $content,
];
dd($error);
}
现在,您可以测试查询了
$this->assertJsonStructure(
'/graphql',
[
'query' => $query,
],
$expected
);
并且,如果失败,它将打印错误信息,并且更易于调试。您可以看到预览here