4

Say we have the following array, $myArray, to check as per var_export:

array (
  0 => AnObject::__set_state(array(
           'id' => 10,
           'name' => 'foo'
  )),
  1 => AnObject::__set_state(array(
           'id' => 23,
           'name' => 'bar'
  )),
  2 => AnObject::__set_state(array(
           'id' => 55,
           'name' => 'baz'
  )),
)

The assertion should pass if this array contains an AnObject which has a name of 'bar'.

I know that if I knew the position of the AnObject value, I could use:

$this->assertAttributeSame('bar', 'name', $myArray[1]);

Is there some way to use $this->assertThat(), or another type of contains to check the entire array and return true of one of the objects has the attribute that matches?

2 Answers 2

6

There is no such built-in assertion and I cannot think of any possibility to combine them to get the expected result.

What I recommend you - is to create a helper method that accepts an array and does the necessary check in a loop.

Other solution is to create completely new assertion just for this case, but I think it is an overkill for this task ;-)

Sign up to request clarification or add additional context in comments.

1 Comment

Depends, if you need that check more often or the actual comparison is getting more and more complex: an own assertion is not that hard to integrate. Just saying.
3

Expanding on the answer provided by zerkms, below is how I approached this exact task:

PHPUnit_Framework_Assert::assertTrue($this->assertArrayContainsSameObject($yourArray, $theObjectToCheck));

To check an array contains an object with the same attributes and values (i.e. not necessarily referencing the same instance):

private function assertArrayContainsSameObject($theArray, $theObject)
{
    foreach($theArray as $arrayItem) {
        if($arrayItem == $theObject) {
            return true;
        }
    }
    return false;
}

To check for the same reference, simply change == to ===.

To solve the original poster's question:

PHPUnit_Framework_Assert::assertTrue($this->assertArrayContainsSameObjectWithValue($yourArray, 'name', 'bar'));


private function assertArrayContainsSameObjectWithValue($theArray, $attribute, $value)
{
    foreach($theArray as $arrayItem) {
        if($arrayItem->$attribute == $value) {
            return true;
        }
    }
    return false;
}

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.