How to Mock Service in Spring Boot Test: Simple Guide
To mock a service in a Spring Boot test, use the
@MockBean annotation on the service field inside your test class. This replaces the real service with a mock, allowing you to define expected behavior using Mockito methods like when() and thenReturn().Syntax
Use @MockBean on a service field in your test class to create a mock instance managed by Spring. Then use Mockito.when() to define what the mock should return when called.
@MockBean: Replaces the real bean with a mock in the Spring context.- Service field: The service you want to mock.
Mockito.when(): Defines mock behavior.
java
import org.springframework.boot.test.mock.mockito.MockBean; import static org.mockito.Mockito.when; @MockBean private YourService yourService; // In test method: when(yourService.someMethod()).thenReturn(someValue);
Example
This example shows a Spring Boot test where a UserService is mocked to return a fixed user name. The test verifies the controller uses the mocked service correctly.
java
import static org.mockito.Mockito.when; import static org.assertj.core.api.Assertions.assertThat; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import org.springframework.test.web.servlet.result.MockMvcResultMatchers; @WebMvcTest(UserController.class) public class UserControllerTest { @Autowired private MockMvc mockMvc; @MockBean private UserService userService; @Test public void testGetUserName() throws Exception { when(userService.getUserName()).thenReturn("Alice"); mockMvc.perform(MockMvcRequestBuilders.get("/username")) .andExpect(MockMvcResultMatchers.status().isOk()) .andExpect(MockMvcResultMatchers.content().string("Alice")); } }
Output
Test passes if the /username endpoint returns 'Alice' as response body.
Common Pitfalls
- Not using
@MockBeanbut creating mocks manually, which won't replace Spring beans. - Forgetting to define mock behavior with
when(), causing null or default returns. - Mocking the wrong bean or missing injection, leading to real service calls.
java
/* Wrong: Manual mock without @MockBean, real service used */ private UserService userService = org.mockito.Mockito.mock(UserService.class); /* Right: Use @MockBean to replace Spring bean */ @MockBean private UserService userService;
Quick Reference
Remember these key points when mocking services in Spring Boot tests:
- Use
@MockBeanto replace beans in Spring context. - Use
Mockito.when()to set mock return values. - Inject mocks with Spring annotations, not manual instantiation.
- Use
@WebMvcTestor@SpringBootTestdepending on test scope.
Key Takeaways
Use @MockBean to replace service beans with mocks in Spring Boot tests.
Define mock behavior with Mockito.when() to control service responses.
Avoid manual mock creation without @MockBean to ensure Spring context replacement.
Use @WebMvcTest for controller layer tests and @SpringBootTest for full context tests.
Always verify that mocks are injected and used to prevent calling real services.