Reputation: 2087
What I have is an array that looks something like this, which gets passed into a method as follows:
$data = array(
'stuff' => 'things',
'otherstuff' => NULL,
'morestuff' => NULL,
);
$object->doStuffWithArray($data);
So I'm writing unit tests, and I need to stub out the doStuffWithArray
behavior by asserting the arguments passed into it. So what I'm doing is something like this:
$object_mock->expects($this->once())
->with($this->equalTo(array(
'stuff' => 'things',
'otherstuff' => NULL,
'morestuff' => NULL,
)));
But this is a bit too strict. I'd like for the unit tests to also pass if the fields whose values are NULL
aren't in the array at all. Is there any way I can do this in PHPUnit?
Upvotes: 2
Views: 1090
Reputation: 31920
Use a callback function instead, with whatever logic you need to confirm the array is valid. e.g. something like:
$object_mock->expects($this->once())
->with($this->callback(function($arg){
if ($arg == array(
'stuff' => 'things',
'otherstuff' => NULL,
'morestuff' => NULL
)) {
return true;
}
if ($arg == array(
'stuff' => 'things'
)) {
return true;
}
return false;
})
);
See https://phpunit.de/manual/current/en/test-doubles.html#test-doubles.mock-objects
"The callback() constraint can be used for more complex argument verification. This constraint takes a PHP callback as its only argument. The PHP callback will receive the argument to be verified as its only argument and should return true if the argument passes verification and false otherwise."
Upvotes: 3