DEV Community

Code Green
Code Green

Posted on

What is Mockito? How to Test SpringBoot Application using Mockito

What is Mockito?

Mockito is a popular Java library used for creating mock objects in unit tests. It allows developers to simulate the behavior of complex objects and interactions, making it easier to test individual components in isolation.

Basic Mockito Example

    import static org.mockito.Mockito.*;

    public class ExampleTest {
        @Test
        public void testSomeMethod() {
            // Create a mock object of the class
            SomeClass mock = mock(SomeClass.class);

            // Define behavior for the mock
            when(mock.someMethod()).thenReturn("Mocked Response");

            // Use the mock in your test
            assertEquals("Mocked Response", mock.someMethod());
        }
    }
Enter fullscreen mode Exit fullscreen mode

Testing a Spring Boot Application with Mockito

In a Spring Boot application, Mockito is often used in conjunction with Spring's testing support to isolate and test service layers or other components without needing to start the entire application context.

Steps to Test a Spring Boot Application with Mockito

  1. Use the @Mock annotation to create mock objects.
  2. Use the @InjectMocks annotation to inject these mocks into the class under test.
  3. Use @SpringBootTest for integration tests if you need to start the Spring context.
  4. Configure behavior using when(...).thenReturn(...).

Example

    import static org.mockito.Mockito.*;
    import org.springframework.boot.test.context.SpringBootTest;
    import org.junit.jupiter.api.Test;
    import org.mockito.InjectMocks;
    import org.mockito.Mock;
    import org.mockito.MockitoAnnotations;

    @SpringBootTest
    public class MyServiceTest {

        @Mock
        private MyRepository myRepository;

        @InjectMocks
        private MyService myService;

        @Test
        public void testGetData() {
            // Arrange
            MockitoAnnotations.openMocks(this);
            when(myRepository.getData()).thenReturn("Mocked Data");

            // Act
            String result = myService.getData();

            // Assert
            assertEquals("Mocked Data", result);
        }
    }
Enter fullscreen mode Exit fullscreen mode

Conclusion

Mockito simplifies unit testing by allowing you to create mock objects and define their behavior. When used with Spring Boot, it enables efficient testing of components in isolation from the application context. This helps ensure that individual units of code work correctly without requiring full application setup.

Top comments (0)