PHPUnit: get arguments to a mock method call
Here's the trick I used. I added this private method to my test class:
private function captureArg( &$arg ) {
return $this->callback( function( $argToMock ) use ( &$arg ) {
$arg = $argToMock;
return true;
} );
}
Then when setting up the mock:
$mock->expects( $this->once() )
->method( 'someMethod' )
->with( $this->captureArg( $arg ) );
After that, $arg
contains the value of the argument passed to the mock.
One thing - inside the closure you still can access $this, in that case it gives you:
$this->patientDao
->expects($this->once())
->method('savePatient')
->will($this->returnCallback(function($patient) {
$this->assertNull($patient->getPhoneNumber());
}));
Make the Mock objects method return the first argument:
$this->patientDao // This is my mock
->expects($this->once())
->method('savePatient') // savePatient() must be called once
->with($this->returnArgument(0));
You can then assert that it is NULL
.
You can make assertions on the argument using returnCallback()
. Remember to call assert functions statically via PHPUnit_Framework_Assert
because you cannot use self
inside a closure.
$this->patientDao
->expects($this->once())
->method('savePatient')
->will($this->returnCallback(function($patient) {
PHPUnit_Framework_Assert::assertNull($patient->getPhoneNumber());
}));