Why am I getting NotAMockException in my Mockito tests?

I’m running unit tests on a Java project using Mockito on Windows 10 with JDK 11 and IntelliJ IDEA 2021.2. While trying to mock a service class, I continuously encounter the NotAMockException from org.mockito.exceptions.misusing. I expected the test to pass after mocking dependencies properly, but it keeps failing. I’ve rechecked that all objects are actually mocks and even reviewed annotations. Could this be related to versioning or setup? How can I resolve this exception?

Encountering NotAMockException with Mockito can be frustrating, but it typically arises when trying to perform operations on an object that isn’t a mock.

Check your test setup to ensure you’re passing a proper mock instance in the places where you use Mockito functionality like when(). This exception often happens if a real object gets passed by mistake due to configuration oversight.

Here is the snippet that worked for me:

MyService myService = Mockito.mock(MyService.class);
Mockito.when(myService.someMethod()).thenReturn("expectedValue");

Make sure every object you’re using with Mockito’s methods is initialized with Mockito.mock(). Developers sometimes overlook this during refactoring, leaving behind non-mocked objects.

Reviewing your annotations such as @Mock or @InjectMocks and verifying correct usage can also prevent this issue. Always double-check the versions of your dependencies, as mismatched versions might lead to unexpected behaviors.

I ran into NotAMockException while working on a legacy project that used multiple testing frameworks. The issue stems from trying to stub or verify an object that wasn’t correctly initialized as a mock.

This usually happens when there’s confusion between mocks and actual objects. Particularly if your test involves mock injection, it can silently fail due to autowiring existing service instances rather than their mocks.

Here’s a different approach:

@Mock
private MyService myService;
@InjectMocks
private MyController myController;

This method ensures proper mock creation and injection. The @Mock annotation helps in distinguishing a mock instance at compile time without manually creating it using Mockito.mock(). Verify that your testing framework’s runner, such as MockitoJUnitRunner, is correctly configured.

The choice of runner can affect how Mockito processes annotations. Switching from JUnit’s default runner to Mockito’s might solve intricate initialization issues.