如何在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
相关产品推荐
相关产品推荐

