Mockery: How to Override Return-Values

Mockery: How to Override Return-Values

I recently introduced Mockery as a replacement for the PHPUnit Mock Framework. And I just noticed that the supposed behavior of overriding return values is different than I expected.

I tried to set up default return values in the setUp() of my TestCase just to override some of them in the  tests.

What I initially thought will work, won’t work:

So, obviously it’s not sufficient to just define the same return value again: It will always return the first value “John Doe”.

But the Mockery interface provides a method called byDefault() that meets our needs to set this definition as default:

Now, the first definition is set as a default value and is considered to be overridden by a following definition for the same method.

So, this works quite well, but unfortunately just once (AFAIK). Drawback: We planned to introduce factories for certain objects we need more often, and in more than one TestCase. But when we try to use it for instance to provide methods like UserFactory::getBasicUser() and UserFactory::getPremiumUser(), it’s not possible to define the premium user as an extension of the basic user, by just getting the basic-user-mock and re-define some expectations. Because then, it’s not possible to re-define it within the test methods a second time.

I don’t think this is a major drawback, because the behavior is sufficient for most of the users. But at least for me it leads me to reconsider my solution. Maybe I take a deeper look into Mockery, trying to figure out how to make it possible to redefine a expectation as default.