Laravel 嵌套数组上的 AssertJsonCount
Laravel AssertJsonCount on a nested array
如何使用索引嵌套数组调用 assertJsonCount
?
在我的测试中,返回以下 JSON:
[[{"sku":"P09250"},{"sku":"P03293"}]]
但是尝试使用assertJsonCount
returns出现以下错误:
$response->assertJsonCount(2);
// Failed asserting that actual size 1 matches expected size 2.
这可能特定于 Laravel,也可能不特定。尽管涉及 Laravel 帮助程序,但此问题可能发生在其他地方。
assertJsonCount
利用 PHPUnit 函数 PHPUnit::assertCount
,它使用 laravel 帮助程序 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;
}
...
我们可以看到返回的JSON是一个嵌套数组,所以按道理我们应该传入一个key为0。
$response->assertJsonCount($expectedProducts->count(), '0');
然而,这将被忽略,因为 assertCount
函数检查是否已使用 is_null
.
传递密钥
为了克服这个问题,我们可以计算所有 children of 0:
$response->assertJsonCount($expectedProducts->count(), '0.*');
这将产生所需的结果。
如何使用索引嵌套数组调用 assertJsonCount
?
在我的测试中,返回以下 JSON:
[[{"sku":"P09250"},{"sku":"P03293"}]]
但是尝试使用assertJsonCount
returns出现以下错误:
$response->assertJsonCount(2);
// Failed asserting that actual size 1 matches expected size 2.
这可能特定于 Laravel,也可能不特定。尽管涉及 Laravel 帮助程序,但此问题可能发生在其他地方。
assertJsonCount
利用 PHPUnit 函数 PHPUnit::assertCount
,它使用 laravel 帮助程序 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;
}
...
我们可以看到返回的JSON是一个嵌套数组,所以按道理我们应该传入一个key为0。
$response->assertJsonCount($expectedProducts->count(), '0');
然而,这将被忽略,因为 assertCount
函数检查是否已使用 is_null
.
为了克服这个问题,我们可以计算所有 children of 0:
$response->assertJsonCount($expectedProducts->count(), '0.*');
这将产生所需的结果。