Mockito @ExtendWith Example

1. Introduction

With the introduction of JUnit 5, the way we run tests has seen some changes. Specifically, JUnit 5 introduced the @ExtendWith annotation as a replacement for the older JUnit 4 @RunWith annotation. For Mockito, this means using the @ExtendWith(MockitoExtension.class) annotation to enable and initialize all Mockito-related functionalities in our test classes.

2. Example Steps

1. Define an interface and its corresponding implementation.

2. Define a service class that utilizes the interface.

3. Create a test class for the service.

4. Annotate the test class with @ExtendWith(MockitoExtension.class).

5. Utilize Mockito annotations such as @Mock and @InjectMocks in the test class.

6. Compose the test methods.

7. Execute the tests.

3. Mockito @ExtendWith Example

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;

interface Store {
    int getItemCount(String item);
}

class Supermarket implements Store {
    @Override
    public int getItemCount(String item) {
        return 10;  // Example value
    }
}

@ExtendWith(MockitoExtension.class)
public class StoreTest {

    @Mock
    Store mockStore;

    @InjectMocks
    Supermarket supermarket;

    @Test
    public void testGetItemCount() {
        // Mocking the getItemCount method of mockStore
        when(mockStore.getItemCount("apple")).thenReturn(5);

        // Calling the getItemCount method
        int count = supermarket.getItemCount("apple");

        // Asserting the result
        assertEquals(5, count);
    }
}

Output:

The test will successfully pass, confirming that the getItemCount method of the Supermarket implementation uses the mocked getItemCount method of the Store interface.

4. Step By Step Explanation

1. We initiated by defining an interface named Store and its corresponding implementation, Supermarket.

2. The StoreTest class is annotated with @ExtendWith(MockitoExtension.class). This ensures all Mockito annotations within the class are auto-initialized without the need to manually invoke any initialization methods.

3. Inside our test class, we utilize the @Mock annotation to declare a mock for the Store interface.

4. The @InjectMocks annotation is then used on Supermarket, indicating that the mock Store should be injected into it.

5. Within the testGetItemCount method, we mock the behavior of the getItemCount method for the mockStore to return 5 when queried with the item "apple".

6. We then invoke the getItemCount method on our supermarket instance and validate the result to ensure it matches the mocked behavior.

7. The @ExtendWith(MockitoExtension.class) annotation ensures automatic initialization and injection, streamlining our test setup and execution.


Comments