Tests let you change code without fear of breaking something. For a Spring Boot REST API, two kinds of tests cover most needs: fast unit tests for service logic with Mockito, and controller tests with MockMvc that check the HTTP layer.
Unit testing a service with Mockito
A service usually depends on a repository. In a unit test you replace the repository with a mock, so the test runs in milliseconds without a database:
@ExtendWith(MockitoExtension.class)
class CourseServiceTest {
@Mock CourseRepository repository;
@InjectMocks CourseService service;
@Test
void throwsWhenCourseMissing() {
when(repository.findById(99L)).thenReturn(Optional.empty());
assertThrows(CourseNotFoundException.class, () -> service.getCourse(99L));
}
}
when(...).thenReturn(...) sets what the mock returns; verify(repository).save(any()) checks that a method was called.
Controller tests with MockMvc
@WebMvcTest(CourseController.class) starts only the web layer. Mock the service with @MockBean (or @MockitoBean in newer Spring versions), then send fake requests:
mockMvc.perform(get("/api/courses/1"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.title").value("Java Full Stack"));
Test the error paths too: a missing course should return 404, and an invalid request body should return 400 with field errors.
What to test first
- Business rules in services (calculations, validations, state changes).
- Each endpoint’s success and main failure responses.
- Edge cases: empty lists, missing records, invalid input.
Good habits
- Name tests after the behaviour:
returns404WhenCourseMissing. - One clear reason to fail per test.
- Run tests in your CI pipeline on every push.
Related: unit testing in Java with JUnit, Spring Boot exception handling and CI/CD explained.
These topics are practised with projects and mock interviews in our Java Full Stack course in Bangalore.
Book a free demo class at our BTM Layout centre, and ask a counsellor for batch details.
