PHPUnit中嵌套的数组键值断言



我试图断言嵌套数组的特定键包含给定值。例如:我有这个:

$owners=[12,15];

以下是我从服务器得到的API响应的密钥:

$response=[
'name'=>'Test',
'type_id'=>2,
'owners'=>[
[
'resource_id'=>132,
'name'=>'Jonathan'
],
[
'resource_id'=>25,
'name'=>'Yosh'
]
]
];

我想检查我的所有者的数组中的至少一个数组的resource_id是否应该为132。我觉得PHPUnit assertArraySubset中有一个断言,但它可能已经被否决了。

有人能告诉我如何在嵌套数组中匹配键和特定值吗?我在PHPUnit框架中看不到任何方法。

PS。很抱歉代码格式不好,我不知道如何在SO上正确使用它。感谢

编写自己的约束以保持测试可读性通常是个好主意。尤其是在这种情况下,当你有一个嵌套的结构。如果只在一个测试类中需要它,则可以使约束成为一个由具有有意义名称的helper方法返回的匿名类。

public function test()
{
$response = $this->callYourApi();
self::assertThat($response, $this->hasOwnerWithResourceId(132));
}
private function hasOwnerWithResourceId(int $resourceId): Constraint
{
return new class($resourceId) extends Constraint {
private $resourceId;
public function __construct(int $resourceId)
{
parent::__construct();
$this->resourceId = $resourceId;
}
protected function matches($other): bool
{
foreach ($other['owners'] as $owner) {
if ($owner['resource_id'] === $this->resourceId) {
return true;
}
}
return false;
}
public function toString(): string
{
return sprintf('has owner with resource id "%s"', $this->resourceId);
}
};
}

最新更新