php - 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 上正确使用它。谢谢
解决方案
编写自己的约束以保持测试的可读性通常是一个好主意。特别是在这种情况下,当您具有嵌套结构时。如果您只在一个测试类中需要它,您可以将约束设置为由具有有意义名称的辅助方法返回的匿名类。
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);
}
};
}
推荐阅读
- c# - Entity Framework Core - 无法删除可选的可为空关系
- javascript - 如何制作树选择选项 - reactjs
- excel - AutoCAD VisualLisp API 和 Excel.Application
- javascript - 无法使用节点获取帖子将数据添加到 HTML 网站
- javascript - ng-select - 打开下拉菜单时,默认情况下会向下滚动
- powershell - 在 YAML 中如何将多个参数传递给 powershell 脚本
- angular - 将 blob url 转换为 Capacitor Share 插件可以使用的 URL
- ruby-on-rails - Rails webpacker 没有包目录
- php - 无效的 JSON 响应块编辑器
- sql - 多列文本搜索