Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHPUnit "with" matcher with array and $this->anything()

I've got a unit test testing a PDOStatement::execute() call with date() as one of the array elements.

Something like:

$stmt->execute(array ('value1', 'value2', date('Ymd'));

The issue is my assertion is using $this->anything() to represent that date function result. I think it's breaking because it's in an array. Is there a good way to handle this?

My assertion looks like:

$mock->expects($this->once())
  ->method('execute')
  ->with(array ('value1', 'value2', $this->anything()));
like image 733
Parris Varney Avatar asked Mar 18 '23 10:03

Parris Varney


1 Answers

You can't pass argument verification methods to with() inside an array. PHPUnit would need to iterate the array and detect the methods. Instead, one of these methods is passed to the with() method for each argument the method should receive.

In your case the method will receive a single argument, so you will employ a single verification. You can't employ a generic verification so you'll need to check the array internals using a callback:

$mock->expects($this->once())
     ->method('execute')
     ->with($this->callback(function($array) {
            return 'value1' == $array[0] && 'value2' == $array[1] && 3 == count($array);
        }));

This is explained in the PHPUnit docs.

like image 174
gontrollez Avatar answered Mar 20 '23 03:03

gontrollez