Back to homepage

Your mock is a joke

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.

public void bar() {
    ITest mock = mock(ITest.class);
    doReturn(new BigDecimal(5)).when(mock).foo(1);;

interface ITest {
    String foo(Number x);

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.

public void bar() {
    Geometry mock = mock(Geometry.class);

interface Geometry {

   * Must return null when x = pi/2
    Double tan(double x);

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 obviosly 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 alread 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.

HugeIface mock = mock(HugeIface.class);

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. This is btw the same reason why I do not like project Lombok. It hides the wrong things.

Make the bad decision visible.

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.