2

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?

1 Answer 1

3

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."

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

1 Comment

Bootiful, simply bootiful, works perfectly. Thanks much!

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.