What triggers NotAMockException in Mockito unit tests?

I’m trying to set up my unit tests using Mockito on IntelliJ with JDK 11. While mocking a dependency, I encountered the error message: “org.mockito.exceptions.misusing.NotAMockException: Argument passed to when() is not a mock! Example of correct stubbing: doThrow(new RuntimeException()).when(mock).someMethod();” I was expecting to properly stub the behavior of my mocked object. I’m using Mockito 3.9.0, and I double-checked my test setup. Could someone explain why this happens and how to resolve it? What should I look out for to avoid this issue in the future?

Sounds like a classic pitfall when setting up your tests. This error pops up a lot when developers mistakenly try to mock something that’s actually not marked as a mock.

The root cause is pretty straightforward: you’re passing a real object or a null reference to the when() function instead of a mocked instance. This often happens if the variable that’s meant to hold the mock wasn’t correctly initialized. Double-check that you’ve called Mockito.mock() in the right spot. Make sure every object used in a when() or doThrow() call is a genuine mock.

Here is the snippet that worked for me:

MockedType mockObject = Mockito.mock(MockedType.class);
when(mockObject.someMethod()).thenReturn(someValue);

The first line ensures you have a legitimate mocked instance of MockedType. Then, use that instance in when(). If you mistakenly use the real object, Mockito throws the NotAMockException.

Before/After: Incorrect:

when(realObject.someMethod())

Correct:

when(mockObject.someMethod())

This ensures you avoid the exception. A pro tip is to initialize mocks in a setup method with @BeforeEach to maintain consistency across your test class. This helps to catch these issues early.

I ran into this confusion while dealing with legacy code. Using the doReturn().when() method is a subtle yet common place to slip up.

The problem occurs if the mock intended for when() isn’t correctly initialized or if the wrong object is being referenced. Unlike the thenReturn() approach, doReturn().when() can be confused with real instances since it’s a procedural setup. Double-checking that each object section in your mock call has been initialized as a mock is crucial.

Here is the snippet that worked for me:

SomeType mockObject = Mockito.mock(SomeType.class);
doReturn(expectedValue).when(mockObject).someMethod();

This code snippet mocks `SomeType`, allowing the method `someMethod()` to return `expectedValue`. Ensure every line with a `doReturn().when()` uses mocked instances.

In my experience, such errors stem from oversight in setting up mocks. I found adding an assertion before mock usage helps confirm that the object is indeed mocked. Keep an eye on imports and ensure you consistently stick to a setup pattern in your tests.