0
0
JunitDebug / FixBeginner · 4 min read

How to Fix Mockito Error in JUnit Tests Quickly

Mockito errors in JUnit often happen because mocks are not initialized properly or annotations are missing. To fix this, use @ExtendWith(MockitoExtension.class) for JUnit 5 or call MockitoAnnotations.openMocks(this) in a setup method to initialize mocks before tests run.
🔍

Why This Happens

Mockito errors in JUnit tests usually occur because the mock objects are not initialized before the test runs. This means Mockito does not know which objects to replace with mocks, causing errors like NullPointerException or org.mockito.exceptions.misusing.MissingMethodInvocationException.

Common causes include missing the Mockito extension annotation or forgetting to open mocks manually.

java
import static org.mockito.Mockito.*;

import org.junit.jupiter.api.Test;
import org.mockito.Mock;

class UserServiceTest {

    @Mock
    UserRepository userRepository; // This mock is not initialized

    @Test
    void testGetUser() {
        when(userRepository.findById(1)).thenReturn(new User(1, "Alice"));
        // This will throw an error because userRepository is null
    }
}
Output
org.mockito.exceptions.misusing.MissingMethodInvocationException: You must call "when" on a mock object. Example of correct usage: when(mock.getArticles()).thenReturn(articles);
🔧

The Fix

To fix Mockito errors in JUnit 5, add @ExtendWith(MockitoExtension.class) to your test class. This tells JUnit to initialize mocks automatically. Alternatively, call MockitoAnnotations.openMocks(this) in a @BeforeEach method to initialize mocks manually.

This ensures your @Mock objects are ready to use in tests.

java
import static org.mockito.Mockito.*;

import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.mockito.junit.jupiter.MockitoExtension;

@ExtendWith(MockitoExtension.class)
class UserServiceTest {

    @Mock
    UserRepository userRepository;

    @Test
    void testGetUser() {
        when(userRepository.findById(1)).thenReturn(new User(1, "Alice"));
        User user = userRepository.findById(1);
        assert user != null && user.getName().equals("Alice");
    }
}
Output
Test passed successfully with no exceptions.
🛡️

Prevention

  • Always use @ExtendWith(MockitoExtension.class) for JUnit 5 tests using Mockito.
  • For JUnit 4, use @RunWith(MockitoJUnitRunner.class) or initialize mocks with MockitoAnnotations.initMocks(this).
  • Check that all @Mock fields are properly annotated and initialized before use.
  • Use IDE or build tool linting to catch missing annotations early.
  • Write simple tests first to confirm mocks work before adding complexity.
⚠️

Related Errors

Other common Mockito errors include:

  • UnnecessaryStubbingException: Happens when you stub a method that is never called. Fix by removing unused stubs or using lenient().
  • NullPointerException: Caused by uninitialized mocks or calling methods on null objects. Fix by initializing mocks properly.
  • InvalidUseOfMatchersException: Occurs when argument matchers are used incorrectly. Fix by using matchers consistently for all arguments.

Key Takeaways

Always initialize Mockito mocks before running tests using proper annotations or setup methods.
Use @ExtendWith(MockitoExtension.class) for JUnit 5 to automate mock initialization.
Check for missing or incorrect Mockito annotations to avoid common errors.
Remove unused stubs to prevent UnnecessaryStubbingException.
Use argument matchers consistently to avoid InvalidUseOfMatchersException.