Jac*_*ero 0 testing phpunit json assert laravel-5
如何assertJsonCount使用带索引的嵌套数组进行调用?
在我的测试中,返回以下 JSON:
[[{"sku":"P09250"},{"sku":"P03293"}]]
Run Code Online (Sandbox Code Playgroud)
但是尝试使用会assertJsonCount返回以下错误:
$response->assertJsonCount(2);
// Failed asserting that actual size 1 matches expected size 2.
Run Code Online (Sandbox Code Playgroud)
这可能是也可能不是 Laravel 特有的。虽然涉及到 Laravel 助手,但这个问题可能发生在其他地方。
assertJsonCount利用 PHPUnit 函数PHPUnit::assertCount,它使用 laravel helper data_get,它具有以下签名:
/**
* Get an item from an array or object using "dot" notation.
*
* @param mixed $target
* @param string|array|int $key
* @param mixed $default
* @return mixed
*/
function data_get($target, $key, $default = null)
{
if (is_null($key)) {
return $target;
}
...
Run Code Online (Sandbox Code Playgroud)
我们可以看到返回的 JSON 是一个嵌套数组,所以逻辑上我们应该传入一个 0 的键。
$response->assertJsonCount($expectedProducts->count(), '0');
Run Code Online (Sandbox Code Playgroud)
但是,这将被忽略,因为assertCount函数检查是否使用is_null.
为了克服这个问题,我们可以计算所有 0 的孩子:
$response->assertJsonCount($expectedProducts->count(), '0.*');
Run Code Online (Sandbox Code Playgroud)
这将产生所需的结果。