0
0
JUnittesting~5 mins

@Mock annotation in JUnit

Choose your learning style9 modes available
Introduction

The @Mock annotation helps create fake objects that imitate real ones. This lets you test parts of your code without using the real objects, making tests faster and simpler.

When you want to test a class but avoid calling real external services like databases or web APIs.
When the real object is slow or hard to set up for testing.
When you want to control the behavior of a dependency to test different scenarios.
When you want to isolate the code under test from other parts of the system.
When you want to verify how your code interacts with its dependencies.
Syntax
JUnit
@Mock
private ClassName mockObject;

Use @Mock on a field to create a mock object of that type.

Remember to initialize mocks with MockitoAnnotations.openMocks(this); in your setup method.

Examples
This creates a mock of a List of Strings.
JUnit
@Mock
private List<String> mockedList;
This creates a mock of the UserService class.
JUnit
@Mock
private UserService userServiceMock;
Sample Program

This test creates a mock List using @Mock. It sets the size to return 3 when called. The test checks that the size method returns 3 and verifies that the size method was called.

JUnit
import static org.mockito.Mockito.*;
import org.junit.jupiter.api.*;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import java.util.List;

public class MockAnnotationTest {

    @Mock
    private List<String> mockedList;

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

    @Test
    void testMockedList() {
        when(mockedList.size()).thenReturn(3);
        Assertions.assertEquals(3, mockedList.size());
        verify(mockedList).size();
    }
}
OutputSuccess
Important Notes

Always initialize mocks before using them to avoid null pointers.

Mocks do not execute real code; they only simulate behavior you define.

Use verify() to check if mocked methods were called as expected.

Summary

@Mock creates fake objects for testing.

It helps isolate the code under test from real dependencies.

Remember to initialize mocks and define their behavior before testing.