Using PHPUnit, I wonder if we can mock an object to test if a method is called with an expected parameter, and a returned value?
In the doc, there are examples with passing parameter, or returned value, but not both…
I tried using this:
// My object to test
$hoard = new Hoard();
// Mock objects used as parameters
$item = $this->getMock('Item');
$user = $this->getMock('User', array('removeItem'));
...
$user->expects($this->once())
->method('removeItem')
->with($this->equalTo($item));
$this->assertTrue($hoard->removeItemFromUser($item, $user));
My assertion fails because Hoard::removeItemFromUser() should return the returned value of User::removeItem(), which is true.
$user->expects($this->once())
->method('removeItem')
->with($this->equalTo($item), $this->returnValue(true));
$this->assertTrue($hoard->removeItemFromUser($item, $user));
Also fails with the following message: “Parameter count for invocation User::removeItem(Mock_Item_767aa2db Object (…)) is too low.“
$user->expects($this->once())
->method('removeItem')
->with($this->equalTo($item))
->with($this->returnValue(true));
$this->assertTrue($hoard->removeItemFromUser($item, $user));
Also fails with the following message: “PHPUnit_Framework_Exception: Parameter matcher is already defined, cannot redefine“
What should I do to test this method correctly.
You need to use
willinstead ofwithforreturnValueand friends.