【问题标题】:Laravel AssertJsonCount on a nested array嵌套数组上的 Laravel AssertJsonCount
【发布时间】:2019-08-31 18:52:15
【问题描述】:

如何使用索引嵌套数组调用assertJsonCount

在我的测试中,返回以下 JSON:

[[{"sku":"P09250"},{"sku":"P03293"}]]

但尝试使用assertJsonCount 会返回以下错误:

$response->assertJsonCount(2);

// Failed asserting that actual size 1 matches expected size 2.

【问题讨论】:

    标签: json testing laravel-5 phpunit assert


    【解决方案1】:

    这可能是也可能不是 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 传递了密钥。

    为了克服这个问题,我们可以计算所有 0 的孩子:

    $response->assertJsonCount($expectedProducts->count(), '0.*');
    

    这将产生所需的结果。

    【讨论】:

      猜你喜欢
      • 2016-09-27
      • 2016-03-27
      • 1970-01-01
      • 2022-08-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-07-07
      • 2019-04-15
      相关资源
      最近更新 更多