4 ms·
The general theory is that, although you're focused on the code under test, if the underlying dependency is not behaving as expected, you want to know that. Moc
by sdhgaiojfsa 9y ago
The general theory is that, although you're focused on the code under test, if the underlying dependency is not behaving as expected, you want to know that. Mocks create an opportunity for your code's expectations about your dependencies' behavior to diverge from reality. So if at all possible, they should be avoided.
There are a few general ways to do this. The best way is to use the real underlying dependency. This should be the default.
If the dependency is too slow to use in the test (e.g. it has a long startup time, or is hosted remotely), the next best thing is to use a fake -- a local implementation of the dep that has the same behavior, but operates in memory on ephemeral data. The best libraries will provide these, and if they don't, you might be able to implement one and contribute it back. Even if you have to maintain it yourself, it often takes less code than describing mock behavior. The downside of fakes vs. the real implementation is that their behavior too can diverge. But this is not a net downside compared to mocks.
If you can't use a fake, the next best thing after that is a stub. See below.
Only if none of these options are viable should you use mocks.
(The position I'm describing is the one referred to as "classicist" in this post: https://martinfowler.com/articles/mocksArentStubs.html https://martinfowler.com/articles/mocksArentStubs.html. I'm not by any means its originator.)