You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在PHPUnit中断言关联数组数组中特定键值条件是否满足?

PHPUnit数组断言测试方案

问题背景

给定以下PHP数组:

$result = [
   [
      "lable" => "first", ["type" => "customer", "balance" => 1000],
   ],
   [
      "lable" => "another", ["type" => "retailer", "balance" => 1500],
   ],
];

需要编写PHPUnit测试,完成两个断言:

  • 断言数组中存在balance大于1200的项
  • 断言数组中存在type为customer的项

测试实现方案

方法一:提取字段结合PHPUnit内置断言

通过array_map提取目标字段,再用assertContains和assertThat完成断言:

public function testResultArrayAssertions()
{
    $result = [
        [
            "lable" => "first", ["type" => "customer", "balance" => 1000],
        ],
        [
            "lable" => "another", ["type" => "retailer", "balance" => 1500],
        ],
    ];

    // 断言存在balance大于1200的项
    $balances = array_map(fn($item) => $item[1]['balance'], $result);
    $this->assertThat(
        $balances,
        $this->logicalOr(...array_map(fn($b) => $this->greaterThan(1200), $balances))
    );

    // 断言存在type为customer的项
    $types = array_map(fn($item) => $item[1]['type'], $result);
    $this->assertContains('customer', $types);
}

方法二:遍历数组直接判断

通过遍历数组检查条件,再用assertTrue断言结果:

public function testResultArrayAssertions()
{
    $result = [
        [
            "lable" => "first", ["type" => "customer", "balance" => 1000],
        ],
        [
            "lable" => "another", ["type" => "retailer", "balance" => 1500],
        ],
    ];

    $hasHighBalance = false;
    $hasCustomerType = false;

    foreach ($result as $item) {
        if ($item[1]['balance'] > 1200) {
            $hasHighBalance = true;
        }
        if ($item[1]['type'] === 'customer') {
            $hasCustomerType = true;
        }
    }

    $this->assertTrue($hasHighBalance, '数组中不存在balance大于1200的项');
    $this->assertTrue($hasCustomerType, '数组中不存在type为customer的项');
}

注意事项

原数组的结构需要特别注意:每个子数组的第二个元素是嵌套的关联数组,因此提取字段时必须使用$item[1]['balance']和$item[1]['type']的语法。

内容的提问来源于stack exchange,提问作者Navid_pdp11

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.19 00:05:42