PHP Laravel单元测试,自定义断言失败消息



我是Laravel的新手,也是一般的单元测试。

我使用拉拉维尔的指南编写了一个简单的测试,

public function testGet(){
$this->get('/api/accounts/1')->assertStatus(200)->assertJsonStructure([
'status','data'
]);
}

运行测试时,它会生成以下失败(这是预期的(:

Time: 127 ms, Memory: 12.00MB
There was 1 failure:
1) TestsUnitAccountApiTest::testGet
Invalid JSON was returned from the route.

我的问题是,有没有办法自定义 Laravel 中所有可用断言的测试失败时生成的消息?对于这种情况,消息

Invalid JSON was returned from the route.

不,您不能轻易修改消息,因为它在 Illuminate/Foundation/Testing/TestResponse 中进行了硬编码.php:

/**
* Validate and return the decoded response JSON.
*
* @param  string|null  $key
* @return mixed
*/
public function decodeResponseJson($key = null)
{
$decodedResponse = json_decode($this->getContent(), true);
if (is_null($decodedResponse) || $decodedResponse === false) {
if ($this->exception) {
throw $this->exception;
} else {
PHPUnit::fail('Invalid JSON was returned from the route.');
}
}
return data_get($decodedResponse, $key);
}

您可以通过覆盖测试响应来获取自定义消息。

相关内容