Testing REST APIs in Java
Automated API testing ensures your endpoints work correctly after every code change. Java developers use MockMvc for unit tests and RestAssured or TestRestTemplate for integration tests.
MockMvc Unit Test
@WebMvcTest(BookController.class)
class BookControllerTest {
@Autowired MockMvc mockMvc;
@MockBean BookService bookService;
@Test
void getBook_returns200() throws Exception {
when(bookService.findById(1L)).thenReturn(new BookDto(1L, "Java Guide"));
mockMvc.perform(get("/api/books/1"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.title").value("Java Guide"));
}
}RestAssured Integration Test
@SpringBootTest(webEnvironment = RANDOM_PORT)
class BookApiIT {
@LocalServerPort int port;
@Test
void createBook_returns201() {
given().port(port).contentType(JSON)
.body("{"title":"New Book"}")
.when().post("/api/books")
.then().statusCode(201)
.body("title", equalTo("New Book"));
}
}Testing Strategy
- Unit test controllers with MockMvc (mock service layer).
- Integration test full stack with @SpringBootTest.
- Use Testcontainers for real database in integration tests.
- Test happy path, validation errors, and auth failures.
Frequently Asked Questions
MockMvc vs RestAssured?▼
MockMvc tests the web layer without starting a server (faster). RestAssured tests against a running server (more realistic). Use both.
