Skip to content
Advertisement

Mockito expecting argument mismatch

I’m writing a Unit test with JUnit 4 and Mockito 4.6.1. I’m mocking an interface method with a specific input value. When a different value is passed, I’m expecting an argument mismatch error, but it’s not being thrown.

Consider the following example:

JavaScript

I’m mocking SomeInterface.test(true) to return 1. This works as expected. Now when I call mock.test(false), I’m expecting an argument mismatch because it’s not defined in the mock setup and strict mode is enabled. Instead, it returns 0 as if it was mocked.

Am I missing something that’s causing this to happen?

Advertisement

Answer

Problem 1. We must enable STRICT_STUBS for test.

STRICT_STUBS – ensures clean tests, reduces test code duplication, improves debuggability. Best combination of flexibility and productivity. Highly recommended. Planned as default for Mockito v4. Enable it via MockitoRule, MockitoJUnitRunner or MockitoSession. See STRICT_STUBS for the details.

According to documentation it can be done via MockitoJUnitRunner.StrictStubs.class

JavaScript

Or strictness rule

JavaScript

Problem 2. Argument strictness does not work when mock definition and mock invocation perform in one source class.
According to Mockito source code:

If stubbing and invocation are in the same source file we assume they are in the test code, and we don’t flag it as mismatch:

Summarise. The working test will be:

JavaScript

On execution we get:

JavaScript

More preferable solution
You can define the default answer with IllegalArgumentException for your mock in case if mock is executed with mismatch arguments. This solution will work always without source file restrictions.

JavaScript

On execution we get:

JavaScript
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement