Failed to claim argument types in PHPUnit

Statement:

$chain->expects($this->once()) ->method('addMethodCall') ->with( 'addOptionsProvider', array( $this->isInstanceOf('Symfony\Component\DependencyInjection\Reference'), $this->equalTo(7) ) ); 

$chain is actually a Definition mock object, and this is the code I would like to test:

 $definition->addMethodCall( 'addOptionsProvider', array(new Reference($id), $priority) ); 

I am starting PHPUnit, so I really don’t know what I am missing. I find a statement of arguments that are difficult to understand. I included an image with a visual difference between the statement and the actual parameters.

PHPUnit_Framework_ExpectationFailedException: The wait did not hold for the method name is equal when called 1 time (s) Parameter 1 to call Symfony \ Component \ dependency injection \ Definition :: addMethodCall ('addOptionsProvider', Array (...)) does not match the expected value.

enter image description here

EDIT : in fact, I ended up with this:

 $chain->expects($this->once()) ->method('addMethodCall') ->with( $this->identicalTo('addOptionsProvider'), $this->logicalAnd( $this->isType('array'), $this->arrayHasKey(0), $this->arrayHasKey(1) ) ); 

But I cannot "go" to the array values ​​for further approval!

+1
source share
1 answer

->with() has a different method signature than you expect.

->with(string|PHPUnit_Framework_Constraint, ...)

means you cannot just pass the array there because PHPUnit is not smart enough to understand what you mean.

The easiest way to do this:

 ->with( 'addOptionsProvider', array( new Reference(1), 7 ) ) 

since it just compares the array.

Another way to mock this (if you need to make method calls on objects, etc.) is to use

 ->with($this->callback(function($arg) { ... } )); 

and make your statements there.

For a complex example, see mock atLeastOnce with a specific value, the rest is not important

+2
source

All Articles