0
0
JunitHow-ToBeginner ยท 4 min read

How to Mock Object in Mockito with JUnit: Simple Guide

To mock an object in Mockito within a JUnit test, use @Mock annotation or Mockito.mock() method to create a mock instance. Then, use when(...).thenReturn(...) to define behavior and verify interactions with verify().
๐Ÿ“

Syntax

Here is the basic syntax to mock an object using Mockito in JUnit:

  • @Mock: Annotation to create a mock object automatically.
  • Mockito.mock(Class.class): Method to create a mock instance manually.
  • when(mock.method()).thenReturn(value): Define what the mock should return when a method is called.
  • verify(mock).method(): Check if a method was called on the mock.
java
import static org.mockito.Mockito.*;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

class MyTest {
    @Mock
    MyService myServiceMock;

    @BeforeEach
    void setup() {
        MockitoAnnotations.openMocks(this); // Initialize mocks
    }

    @Test
    void testMock() {
        when(myServiceMock.getData()).thenReturn("mocked data");
        String result = myServiceMock.getData();
        verify(myServiceMock).getData();
        // Assertions here
    }
}
๐Ÿ’ป

Example

This example shows how to mock a service object in a JUnit test using Mockito. It mocks the getData() method to return a fixed string and verifies the method call.

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

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

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

public class MyServiceTest {
    @Mock
    MyService myServiceMock;

    @BeforeEach
    void init() {
        MockitoAnnotations.openMocks(this);
    }

    @Test
    void testGetData() {
        when(myServiceMock.getData()).thenReturn("mocked data");

        String data = myServiceMock.getData();

        verify(myServiceMock).getData();
        assertEquals("mocked data", data);
    }
}
Output
PASSED
โš ๏ธ

Common Pitfalls

Common mistakes when mocking with Mockito in JUnit include:

  • Not initializing mocks with MockitoAnnotations.openMocks(this) or @ExtendWith(MockitoExtension.class).
  • Mocking final classes or methods without enabling the inline mock maker (Mockito 2+).
  • Forgetting to use when(...).thenReturn(...) before calling the mock method.
  • Using real objects instead of mocks by mistake.

Example of wrong and right ways:

java
import static org.mockito.Mockito.*;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;

class Service {
    String getValue() { return "real"; }
}

public class ServiceTest {
    @Mock
    Service serviceMock;

    @BeforeEach
    void setup() {
        // Missing this line causes NullPointerException
        MockitoAnnotations.openMocks(this);
    }

    @Test
    void testWrong() {
        // This will throw NullPointerException because mock not initialized
        when(serviceMock.getValue()).thenReturn("mocked");
    }

    @Test
    void testRight() {
        MockitoAnnotations.openMocks(this);
        when(serviceMock.getValue()).thenReturn("mocked");
        String val = serviceMock.getValue();
        verify(serviceMock).getValue();
    }
}
๐Ÿ“Š

Quick Reference

ActionSyntaxDescription
Create mock with annotation@Mock MyClass myMock;Declares a mock object to be initialized.
Initialize mocksMockitoAnnotations.openMocks(this);Initializes @Mock annotated fields.
Create mock manuallyMyClass myMock = Mockito.mock(MyClass.class);Creates mock instance without annotation.
Stub method callwhen(myMock.method()).thenReturn(value);Defines return value for method call.
Verify method callverify(myMock).method();Checks if method was called on mock.
โœ…

Key Takeaways

Use @Mock annotation with MockitoAnnotations.openMocks(this) to create and initialize mocks.
Define mock behavior using when(...).thenReturn(...) before calling the mock method.
Always verify interactions with verify(mock).method() to ensure expected calls.
Avoid forgetting mock initialization to prevent NullPointerException.
Mockito.mock(Class.class) can create mocks manually without annotations.