0
0
JunitHow-ToBeginner ยท 4 min read

How to Use Mockito with JUnit for Unit Testing

To use Mockito with JUnit, add Mockito annotations like @Mock to create mock objects and use @ExtendWith(MockitoExtension.class) to enable Mockito support in JUnit 5. Then, write test methods that use when() and verify() to define mock behavior and check interactions.
๐Ÿ“

Syntax

Mockito works with JUnit by using annotations and methods to create and manage mock objects. Key parts include:

  • @Mock: Creates a mock instance of a class or interface.
  • @InjectMocks: Injects mocks into the tested class.
  • @ExtendWith(MockitoExtension.class): Enables Mockito support in JUnit 5 tests.
  • when(...).thenReturn(...): Defines mock method behavior.
  • verify(...): Checks if a mock method was called.
java
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;

import static org.mockito.Mockito.*;
import static org.junit.jupiter.api.Assertions.*;

@ExtendWith(MockitoExtension.class)
class ExampleTest {

    @Mock
    Dependency dependency;

    @InjectMocks
    Service service;

    @Test
    void testService() {
        when(dependency.getData()).thenReturn("mocked data");

        String result = service.process();

        assertEquals("mocked data processed", result);
        verify(dependency).getData();
    }
}

class Dependency {
    String getData() { return "real data"; }
}

class Service {
    private final Dependency dependency;
    Service(Dependency dependency) { this.dependency = dependency; }
    String process() { return dependency.getData() + " processed"; }
}
๐Ÿ’ป

Example

This example shows a simple test using Mockito with JUnit 5. It mocks a Dependency class, injects it into a Service class, and verifies the service returns the expected processed string.

java
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;

import static org.mockito.Mockito.*;
import static org.junit.jupiter.api.Assertions.*;

@ExtendWith(MockitoExtension.class)
class ServiceTest {

    @Mock
    Dependency dependency;

    @InjectMocks
    Service service;

    @Test
    void processReturnsMockedData() {
        when(dependency.getData()).thenReturn("mocked data");

        String result = service.process();

        assertEquals("mocked data processed", result);
        verify(dependency).getData();
    }
}

class Dependency {
    String getData() { return "real data"; }
}

class Service {
    private final Dependency dependency;
    Service(Dependency dependency) { this.dependency = dependency; }
    String process() { return dependency.getData() + " processed"; }
}
Output
Test passed
โš ๏ธ

Common Pitfalls

Common mistakes when using Mockito with JUnit include:

  • Not using @ExtendWith(MockitoExtension.class) in JUnit 5, so mocks are not initialized.
  • Forgetting to annotate fields with @Mock, resulting in null mocks.
  • Not using @InjectMocks to inject mocks into the tested class.
  • Using when() on final or static methods, which Mockito cannot mock by default.
  • Not verifying mock interactions, missing test coverage on behavior.

Example of a wrong and right way:

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

import static org.mockito.Mockito.*;
import static org.junit.jupiter.api.Assertions.*;

@ExtendWith(MockitoExtension.class)
class WrongRightTest {

    // Wrong: missing @Mock annotation, dependency is null
    Dependency dependency;

    @Test
    void testWithoutMock() {
        // This will throw NullPointerException
        // when(dependency.getData()).thenReturn("mocked");
    }

    // Right: properly annotated mock
    @Mock
    Dependency correctDependency;

    @Test
    void testWithMock() {
        when(correctDependency.getData()).thenReturn("mocked");
        assertEquals("mocked", correctDependency.getData());
        verify(correctDependency).getData();
    }
}

class Dependency {
    String getData() { return "real data"; }
}
๐Ÿ“Š

Quick Reference

Here is a quick cheat sheet for using Mockito with JUnit 5:

FeatureUsage
Enable Mockito in JUnit 5@ExtendWith(MockitoExtension.class)
Create a mock object@Mock private ClassName mock;
Inject mocks into tested class@InjectMocks private TestedClass tested;
Define mock behaviorwhen(mock.method()).thenReturn(value);
Verify method callverify(mock).method();
Reset mocksreset(mock);
โœ…

Key Takeaways

Always use @ExtendWith(MockitoExtension.class) to enable Mockito in JUnit 5 tests.
Annotate dependencies with @Mock and the tested class with @InjectMocks for automatic injection.
Use when(...).thenReturn(...) to define mock behavior and verify(...) to check interactions.
Avoid mocking final or static methods without additional tools as Mockito cannot mock them by default.
Verify mock interactions to ensure your code behaves as expected.