R
Rishtaara
Spring Boot Fundamentals
Lesson 7 of 8Article18 min

Testing Spring Boot Applications

Testing Spring Boot Applications

Testing strategy

  • Unit tests for service logic with mocks.
  • Slice tests (`@WebMvcTest`) for controller contracts.
  • Integration tests for repository and full app flow.

Controller test example

MockMvc happy-path test
@WebMvcTest(CourseController.class)
class CourseControllerTest {
  @Autowired private MockMvc mockMvc;
  @MockBean private CourseService courseService;

  @Test
  void shouldReturnCourseList() throws Exception {
    when(courseService.list()).thenReturn(List.of(new CourseDto(1L, "Spring Boot", "Beginner")));

    mockMvc.perform(get("/api/courses"))
      .andExpect(status().isOk())
      .andExpect(jsonPath("$[0].title").value("Spring Boot"));
  }
}