Summer Sale! All accounts are 50% off this week.

orest's avatar
Level 13

To mock or not ?

Given an action class that stores users that can be called from multiple places, for example from a controller, command, job or whatever else.

class StoreUsers{
	public function execute(array $users)
    {
        // do stuff
     }
}

Which way you would test the command or controller that is using the StoreUsers class ?

  • Would you mock the StoreUsers and make sure that execute is called with the right data or

  • Would you let it execute and check that the users are stored in the database ?

0 likes
6 replies
tisuchi's avatar

@orest My understanding, if your execute() method does not contain so much dependency (depends on other class/methods), or does not have any external service call (API), then I would I don't mock it.

My standpoint, If I call it in the test, I will get the real output of the code.

tisuchi's avatar

@orest Ofcourse you can mock it, which means you are not getting the real behaviour from the code instead of pretending the same behaviour where the real code might not behave same all the time :)

1 like
orest's avatar
Level 13

i avoid mocking for the same reason you mentioned. i want to make sure that i get the real behaviour. I was just curious to see how other people handle that because i've seen quite a few times people mocking almost everything.

Would you mock it if the StoreUsers class had dependencies in it ?

tisuchi's avatar

@orest

Would you mock it if the StoreUsers class had dependencies in it?

Imagine that storeUsers() method needs 4 more classes to complete its task.

In that case, my test is busy building the environment by preparing all dependencies for running the storeUsers method.

Now if I mock the storeUsers() which will return expected behavior, then I can fully focus on the main purpose of the test instead of preparing all the relevant stuff to run a method only.

1 like
orest's avatar
Level 13

@tisuchi

I am assuming, that is considering that the dependencies cannot be resolved automatically.

For example if you call app(StoreUsers::class) it will automatically resolve the dependencies ( if they can be resolved )

But you would compromise the "real behaviour" in the case that it would require more steps to resolve the 4 dependencies of the StoreUsers class, just to keep the test more compact. That is an interesting approach, i will have that in mind.

tisuchi's avatar

@orest

I am assuming, that is considering that the dependencies cannot be resolved automatically.

Yes.

But you would compromise the "real behaviour" in the case that it would require more steps to resolve the 4 dependencies of the StoreUsers class, just to keep the test more compact. That is an interesting approach, i will have that in mind.

Yes, that's true. I compromise the real behavior when mocking. Totally agree with you.

Please or to participate in this conversation.