首页 > 解决方案 > 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 上正确使用它。谢谢

标签: phpphpunitcodeception

解决方案


编写自己的约束以保持测试的可读性通常是一个好主意。特别是在这种情况下,当您具有嵌套结构时。如果您只在一个测试类中需要它,您可以将约束设置为由具有有意义名称的辅助方法返回的匿名类。

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);
        }
    };
}

推荐阅读