[英]Nested array key value assertion in 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 上正確使用它。 謝謝
編寫自己的約束以保持測試的可讀性通常是一個好主意。 特別是在這種情況下,當您具有嵌套結構時。 如果您只在一個測試 class 中需要它,您可以將約束設置為匿名 class 由具有有意義名稱的輔助方法返回。
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);
}
};
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.