How do I test the following code without hitting the database?
(This is php + phpunit btw)
Much untestable. Very sad. Wow.
This is a stopgap measure. Unfortunately, we do not live in a perfect world where all your dependencies are injected.
It typically is not okay to fake the class that you are currently testing. However, if you are testing legacy code for which you need a temporary fix and save the issue to come back to, you can try the following “solution”.
See this resource about mocking the class being tested.
An example use case is you may have an instantiation of an object that is not critical to the usage of that function. For instance, if the instantiation of this object lives in one logic block of an if-else statement.
Fine. You have been warned. Let’s wrap it! Check dis outttt:
Yay! You now have a working tested version!
But what about this sadness about faking the class you are testing? What are the alternatives? Dependency injection to the rescue!
When possible, refactor the code to this:
Now testing is easy!
And look! You’re not mocking YayAClass. All is well with the world. ❤