Why am I getting NotAMockException with Mockito in my Java tests?

I’m currently working on a Java project using Mockito for unit testing in Eclipse IDE on Windows 10. Whenever I run my tests, I encounter the org.mockito.exceptions.misusing.NotAMockException. I’ve double-checked that I’m passing proper mock objects, but I can’t seem to pinpoint why this issue persists. I expected my tests to execute smoothly without throwing this exception. Is there a common oversight or configuration issue that could be causing this error? Any guidance would be greatly appreciated!

This issue often occurs when there’s an attempt to stub or verify a method on an object that isn’t actually a mock. This can happen if the object was created using a new instance or isn’t set up with Mockito’s mock() method. You need to ensure that all interactions are performed on properly mocked objects.

Here is the snippet that worked for me:

import static org.mockito.Mockito.*;

List mockedList = mock(List.class);
mockedList.add("one");
verify(mockedList).add("one");

This code demonstrates creating a mock using mock(), performing an action, and then verifying that interaction. The key point is ensuring the object was created using mock().

Before changing your code, confirm that you’re not accidentally creating objects using new List() or similar patterns, because those instances will not be mocks. Also double-check your imports to ensure Mockito’s classes are being used.

Sometimes IDE auto-imports can bring in incorrect classes, which may also lead to unexpected issues.

I’ve faced this exact scenario before and discovered that the issue came from mixing real objects with mocks.

NotAMockException occurs when Mockito operations such as when(), verify(), or doReturn() are used on objects that were not created as mocks. This usually means that somewhere in your test setup a real object slipped in instead of a mocked one.

One approach that helps prevent this is using Mockito annotations to initialize mocks automatically:

public class TestClass {

  @Mock
  List mockedList;

  @Before
  public void initMocks() {
    MockitoAnnotations.initMocks(this);
  }
}

With this setup, any field marked with @Mock will be initialized as a Mockito mock before the tests run.

Also watch for constructors or manual object creation inside tests that might override or replace your mocked instances. That’s a common source of this exception.