While unit testing in PHPUnit, I'm in a situation where I need to check if an array contains al least one object of a specific type.
Here's a trivial example of what I'm looking for
$obj_1 = new Type1;
$obj_2 = new Type2;
$container = array( $obj_1, $obj_2 );
// some logic and array manipulation here
// need something like this
$this->assertArrayHasObjectOfClass( 'Type1', $container );
Obviously I can do that with custom code, but is there any assertion (or combination of them) which allows me to do that?
I need to do that many times in multiple tests so, if the assertion I need doesn't esist, how do I extend the set of PHPUnit assertions?
EDIT: custom solution with trait
As suggested by Vail, I came up with a custom solution for this using traits. Here's a semplified version.
// trait code
trait CustomAssertTrait
{
public function assertArrayHasObjectOfType( $type, $array, $message = '' ) {
$found = false;
foreach( $array as $obj ) {
if( get_class( $obj ) === $type ) {
$found = true;
break;
}
}
$this->assertTrue( $found, $message );
}
}
// test code
class CustomTest extends PHPUnit_Framework_TestCase {
use CustomAssertTrait;
// test methods...
}
breakout of the loop.