15 June 2019

Mockito 2.0 and a thousand failing unit tests

Wow this killed me for a few days. I upgraded my long since out of date Mockito to the latest version 2.28.2 from version 1.something. Instantly 90% of my unit tests failed. Queue a long drawn out investigation to try and figure out what was happening. Numerous culprits were held under the spotlight and shaken down.

Ultimately, (as is usually the case) the answer was somewhat simple. My mock methods had all been declared irrelevant by this change to Mockito:

anyString() no longer accepts nulls.

So a mock method like this:

when(mockClass.mockMethod(anyString())).thenReturn("All your base are belong to me")

Simply stopped returning anything.

https://github.com/mockito/mockito/issues/185

The workaround is either to use any() or a deliberate null.

when(mockClass.mockMethod(any())).thenReturn("All your base are belong to me")


when(mockClass.mockMethod(isNull())).thenReturn("All your base are belong to me")


I hope this helps someone avoid my mistakes. Happy coding.