Mocking in Unit Tests
Debate on the use and pitfalls of mocks in unit testing, advocating alternatives like integration tests, fakes, or avoiding mocks for tightly coupled code.
Activity Over Time
Top Contributors
Keywords
Sample Comments
If you're doing extensive mocking, then you should be doing integration tests instead.
If you don't use mocks then won't you just end up with integration tests?
It's kind of unavoidable once you're trying to do unit tests with mocks. You either end up with interfaces for everything and a dependency injection framework, or you end up with some very non-isolated tests that take ages to run because they need inseparable parts of the whole real system.
Don't mock everything, by mocking everything, you are testing... nothing.
I agree. I mostly only use mocks for external service dependencies (apart from primary application database), or library features that are very problematic to use in test. A lot of code simply should not be unit tested - if an integration test can cover the same paths its far better in the long run. Performance can become an issue but it is easier to deal with that than to spend so much time maintaining and debugging mock constructs.
Why I don't mock:https://blog.metaobject.com/2014/05/why-i-don-mock.html
Because people hear “unit tests” and “integration test” and “behavior test” and bend over backwards to start DI and mock every single little thing and be very careful about organizing things in that way, which is a huge anti pattern in my experience. You should DI/mock only when you have no other choice (eg you need to corrupt the data returned by an I/O call to test some corner condition). Generally, the less DI/mocking/supporting code just for testing purposes you have, the
Why would it be of concern? I think mocks have a good place in unit tests. I generally believe the premise of unit tests is to test your code against specific pre-conditions. If those pre-conditions cannot be created in a unit testing environment then mocks are justified. I would, however, be very way of mocks moving past unit testing and into integration or system testing (or other varieties like failure injection testing, performance testing, etc.). Mocks have their uses & their limitation
Seemingly unpopular opinion (with a lens of Go programming): Don't mock dependencies. It is brittle. Stub/fake with dependency injection. It is unimportant that a function was called N times with arguments foo and bar. What is important is that unit tests validate that units output what they should output (success and error cases) and that integration tests ensure things work together.
Mocks mean your code is too tightly coupled. You should be able to unit test your code by creating only fake data.Things like dependency injection increase coupling to the point where you have to mock. Avoid dependency injection and other complexity within complexity features.