It looks like using returnCallback()
did the job.
$employee
->expects($this->any())
->method('getEmploymentBegin')
->will($this->returnCallback(
function () { return date_create('05.11.2012'); }
));
Question
I am mocking a method from a class that looks like this:
class Employee {
/**
* @return \DateTime
*/
public function getEmploymentBegin()
{
return clone $this->employmentBegin;
}
My mock looks like:
$employee = $this->getMockBuilder('\MyApp\Employee')->disableOriginalConstructor()->getMock();
$employee
->expects($this->any())
->method('getEmploymentBegin')
->will($this->returnValue(date_create('05.11.2012')));
Later the code that I am testing needs to manipulate the date:
$a= $this->employee->getEmploymentBegin();
$b = $this->employee->getEmploymentBegin();
$b->modify('+ 6 weeks')->modify('yesterday');
My issue is that at the end Both $a
and $b
end-up with the same reference.
Solution 2
It looks like using returnCallback()
did the job.
$employee
->expects($this->any())
->method('getEmploymentBegin')
->will($this->returnCallback(
function () { return date_create('05.11.2012'); }
));
OTHER TIPS
You can change your mock to:
$date = date_create('05.11.2012');
$employee
->expects($this->any())
->method('getEmploymentBegin')
->will($this->onConsecutiveCalls(clone $date, clone $date));
The clone
seems like an important implementation detail. I'm not sure how to deal with that. Maybe getEmploymentBegin
should return a simple type (like a string). Anything that wants to do date arithmetic can then upgrade it to a Date
.