PHPUnit: assert a parameter when passed to mock an object

In the code below

$mockObject->expects($this->at(0)) ->method('search') ->with($searchConfig) ->will($this->returnValue([])); 

This line will automatically make the statement that when the search method is called, it must contain the parameters $searchConfig . In this case, we must ensure that $searchConfig fully consistent, but sometimes it is difficult if it is an array or an object.

Is there any possible way for PHPUnit to call any particular method in order to claim that it contains arguments, passed in the form we want?

For example, I can create a close function to assert, as shown below, instead of the ->with() method

 function ($config){ $this->assertFalse(isset($config['shouldnothere'])); $this->assertTrue($config['object']->isValidValue()); } 
+8
php unit-testing phpunit
source share
1 answer

You can use ->with($this->callback()) and pass a closure to perform more complex statements in the argument.

From PHPUnit Docs

The callback () constraint can be used for a more complex check argument. This restriction takes a PHP callback as the only argument. The PHP callback will receive an argument that will be tested as its only argument and should return TRUE if the argument passes validation and FALSE otherwise.

Example 10.13: More complex argument checking

getMock ('Observer', array ('reportError'));

  $observer->expects($this->once()) ->method('reportError') ->with($this->greaterThan(0), $this->stringContains('Something'), $this->callback(function($subject){ return is_callable(array($subject, 'getName')) && $subject->getName() == 'My subject'; })); $subject = new Subject('My subject'); $subject->attach($observer); // The doSomethingBad() method should report an error to the observer // via the reportError() method $subject->doSomethingBad(); } } ?> 

So your test will be as follows:

 $mockObject->expects($this->at(0)) ->method('search') ->with($this->callback( function ($config){ if(!isset($config['shouldnothere']) && $config['object']->isValidValue()) { return true; } return false; }) ->will($this->returnValue([])); 
+18
source share

All Articles