【问题标题】:Nested array key value assertion in PHPUnitPHPUnit中的嵌套数组键值断言
【发布时间】:2020-10-26 21:43:08
【问题描述】:

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

$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 上正确使用它。 谢谢

【问题讨论】:

    标签: php phpunit codeception


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 2020-02-16
      • 2013-05-02
      • 2011-01-28
      • 1970-01-01
      • 2020-10-30
      • 2016-09-14
      • 1970-01-01
      • 2012-12-07
      • 2018-11-27
      相关资源
      最近更新 更多