1

I am trying to assert that specific key of my nested array contains given value. For example: I have this:

$owners=[12,15];

Here is API response's key that I get from server:

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

I want to check that the at least one of my owner's array should have resource_id as 132. I feel there has been an assertion in PHPUnit assertArraySubset but it may have been deprecated.

Can anyone tell how I can match key with specific value in nested array? I could not see any method in PHPUnit framework for that.

PS. Sorry for poor formatting of code, I don't know how to properly intend it here on SO. Thanks

1 Answer 1

2

It's often a good idea to write own constraints to keep tests readable. Especially in cases like this when you have a nested structure. If you need it in just one test class you can make the constraint an anonymous class returned by a helper method with a meaningful name.

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);
        }
    };
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.