Your mock is a joke

Dominik Moštěk
2 min readJul 19, 2022

--

Posted on October 18, 2019

When writing tests I am trying to avoid mock frameworks at any cost. Here is why

Your mock object is a joke; that object is mocking you. For needing it. ~ Rich Hickey

It is not compile safe

This code is perfectly compilable, but it will fail at runtime.

We should take advantage of compiler whenever possible. Not bypass it. This would not happen with anonymous class or a lambda.

Make wrong use hard or even impossible

So easy to break contract

When defining a mock I can violate method contract very easily.

I have violated the contract defined in the javadoc. I know, if it is not compile-time safe its never guaranteed, so how not using mockito helps? For example by using dummy implementation. When implementing an interface you obviously tend to read its doc. You should do that in case of mockito object also but who does that, right? And the dummy implementation has two more advantages — once implemented according the javadoc it will adhere to its contract whenever used. And it can be unit tested for it. So even if Josh read the javadoc and created the mockito object correctly, Charles might not. If Charles reused the dumy implementation the concern of adhering to the contract is already solved.

Using mock framework hide code smells

I think you should feel the pain of every bad design decision you have made. Consider an interface with a lot of methods violating SRP.

If you use mock frameowrk it ill hide the pain and you wont feel it and have the urge to fix it.)

This is very easy and comfortable, right? The bad design is still there but it is not that obvious. If you use anonymous class, for example the poor design choice will come to a sunlight.

You have a lot of code you dont need and most methods contains no code or just return null. Thus possible violation of SRP or/and ISP.

Make the bad decision visible.

More on that in my another post — Signalling in programming.

Your code should be !easily! testable without any framework

The use cases are at the center. Always! Databases and frameworks are details ~Robert C. Martin, No DB

If you need a framework to test your use cases there is somethig wrong. Some technical details are obviously leaking into your use cases. That is the case with @InjectMocks annotation.

Originally published at https://dominikmostek.cz.

--

--