Dung (Donny) Nguyen

Senior Software Engineer

Mockito

Mockito is a popular Java library used for unit testing in Java applications. It allows developers to create mock objects, which are simulated objects that mimic the behavior of real objects. Mockito is widely used for testing purposes because it simplifies the process of creating and managing mock objects, enabling developers to write more effective and reliable unit tests.

Key Features of Mockito

Basic Usage

Here’s a simple example to illustrate how Mockito can be used in a unit test:

  1. Dependencies:
    • Add Mockito dependencies to your project’s pom.xml if you are using Maven:
      <dependency>
        <groupId>org.mockito</groupId>
        <artifactId>mockito-core</artifactId>
        <version>3.11.2</version>
        <scope>test</scope>
      </dependency>
      
  2. Creating a Mock Object:
    import static org.mockito.Mockito.*;
    import org.junit.jupiter.api.Test;
    
    class MyServiceTest {
         
      @Test
      void testMyServiceMethod() {
        // Create a mock object for the dependency
        MyDependency mockDependency = mock(MyDependency.class);
           
        // Define behavior for the mock object
        when(mockDependency.someMethod()).thenReturn("Mocked Result");
           
        // Create an instance of the class under test, injecting the mock dependency
        MyService myService = new MyService(mockDependency);
           
        // Perform the test
        String result = myService.myServiceMethod();
           
        // Verify the expected result
        assertEquals("Mocked Result", result);
           
        // Verify that the mock method was called once
        verify(mockDependency, times(1)).someMethod();
      }
    }
    

Example Explanation

Benefits of Using Mockito

Mockito is a powerful tool for enhancing the quality of your unit tests, making it easier to test interactions between objects and ensure your code behaves as expected.