Home Arrow Icon Knowledge base Arrow Icon Global Arrow Icon Example code for Mockito's mock() method


Example code for Mockito's mock() method


Sure, here's an example of using Mockito's `mock()` method to create mock objects in Java:

java
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;

import java.util.List;

import static org.mockito.Mockito.when;

class MockitoExampleTest {
    @Test
    void testMockObject() {
        // Create a mock object using mock()
        List<String> mockedList = Mockito.mock(List.class);

        // Set up behavior for the mock object
        when(mockedList.get(0)).thenReturn("mocked value");

        // Interact with the mock object
        String result = mockedList.get(0);
        System.out.println(result); // Output: "mocked value"

        // Verify interactions with the mock object
        Mockito.verify(mockedList).get(0);
    }
}

In this example:

1. We create a mock object of type `List` using the `mock()` method from Mockito.

2. We set up the behavior of the mock object using `when()` and `thenReturn()`. In this case, we specify that when the `get(0)` method is called on the mock, it should return the string "mocked value".

3. We interact with the mock object by calling the `get(0)` method, which returns the mocked value.

4. Finally, we verify that the `get(0)` method was called on the mock object using `verify()`.

To handle the cleanup of mock objects created using `mock()`, you can use one of the cleanup mechanisms provided by Mockito:

- Using `MockitoJUnitRunner` or `MockitoExtension`:

java
  @ExtendWith(MockitoExtension.class)
  class MockitoExampleTest {
      // ...
  }
  

- Using `MockitoRule`:

java
  public class MockitoExampleTest {
      @Rule
      public MockitoRule mockitoRule = MockitoJUnit.rule();

      // ...
  }
  

- Manual cleanup with `reset()`:

java
  @AfterEach
  void tearDown() {
      Mockito.reset(mockedList);
  }
  

- Using `MockitoSession`:

java
  @Test
  void testMockObject() {
      try (MockitoSession mockitoSession = Mockito.mockitoSession().initMocks(this).startMocking()) {
          // ...
      }
  }
  

By using these cleanup mechanisms, you can ensure that mock objects created with `mock()` are properly cleaned up after each test, preventing any unintended side effects or leaks between tests.