Sub topic 13
Trying the endpoints with curl and MockMvc
This chapter assumes you have the BookController, CreateBookRequest, and ApiExceptionHandler from the earlier chapters. It also assumes a Book record with id, title, author, and pages, and a BookService bean. You should know basic JUnit and Mockito.
Two ways to check an endpoint
You can send real HTTP requests to a running application with curl. You can also send simulated requests to the controller inside a test with MockMvc. curl shows what a client sees. MockMvc gives repeatable checks that run in your build.
Trying the endpoints with curl
Start the application, then send one request for each input style.
curl -i http://localhost:8080/api/books/42
curl -i "http://localhost:8080/api/books?author=Le%20Guin&page=0&size=10"
curl -i -X POST http://localhost:8080/api/books \
-H "Content-Type: application/json" \
-d '{"title":"A Wizard of Earthsea","author":"Ursula K. Le Guin","pages":183}'The -i flag prints the status line and headers. You need them to see 201 Created and the Location header. Quote any URL that contains ? or &, or the shell will interpret them.
Then send bad input on purpose:
curl -i http://localhost:8080/api/books/abc
curl -i -X POST http://localhost:8080/api/books \
-H "Content-Type: application/json" \
-d '{"title":"","author":"Ursula K. Le Guin","pages":-5}'The first request should return 400 with a ProblemDetail body that names the parameter id. The second should return 400 with an errors map for title and pages.
Testing with MockMvc
@WebMvcTest loads only the web layer: controllers, @RestControllerAdvice classes, and Jackson. It does not load BookService, so you replace it with a mock. @MockitoBean is available from Spring Boot 3.4. On older versions, use @MockBean.
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import java.util.List;
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.http.MediaType;
import org.springframework.test.context.bean.override.mockito.MockitoBean;
import org.springframework.test.web.servlet.MockMvc;
@WebMvcTest(BookController.class)
class BookControllerTest {
@Autowired
MockMvc mvc;
@MockitoBean
BookService service;
@Test
void pathVariableIsBoundAsLong() throws Exception {
when(service.get(42L)).thenReturn(new Book(42L, "Dune", "Frank Herbert", 412));
mvc.perform(get("/api/books/42"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.title").value("Dune"));
}
@Test
void queryParametersAreBound() throws Exception {
when(service.search("Le Guin", 0, 10)).thenReturn(List.of());
mvc.perform(get("/api/books")
.param("author", "Le Guin")
.param("page", "0")
.param("size", "10"))
.andExpect(status().isOk());
verify(service).search("Le Guin", 0, 10);
}
@Test
void nonNumericIdReturns400() throws Exception {
mvc.perform(get("/api/books/abc"))
.andExpect(status().isBadRequest())
.andExpect(jsonPath("$.detail").value("Invalid value for parameter 'id'"));
}
@Test
void validBodyReturns201WithLocation() throws Exception {
when(service.create(any(CreateBookRequest.class)))
.thenReturn(new Book(7L, "Dune", "Frank Herbert", 412));
mvc.perform(post("/api/books")
.contentType(MediaType.APPLICATION_JSON)
.content("{\"title\":\"Dune\",\"author\":\"Frank Herbert\",\"pages\":412}"))
.andExpect(status().isCreated())
.andExpect(header().string("Location", "http://localhost/api/books/7"));
}
@Test
void invalidBodyReturns400WithFieldErrors() throws Exception {
mvc.perform(post("/api/books")
.contentType(MediaType.APPLICATION_JSON)
.content("{\"title\":\"\",\"author\":\"Frank Herbert\",\"pages\":-5}"))
.andExpect(status().isBadRequest())
.andExpect(jsonPath("$.errors.title").exists())
.andExpect(jsonPath("$.errors.pages").exists());
}
}Each test uses one input style. .param(...) fills the query string, the URL template fills the path, and .content(...) with .contentType(...) supplies the body.
Common mistakes
- Forgetting to quote a URL in curl, so the shell cuts it at
&. - Expecting a real database in
@WebMvcTest. Only the web layer is loaded. - Checking the
Locationheader againstlocalhost:8080. MockMvc useshttp://localhostwith no port.
Exercise
Write the MockMvc call that checks a request with a missing required query parameter. The since parameter of /api/books/published has no default. What status do you expect from Spring's default handling, and why?
Show answer
Use mvc.perform(get("/api/books/published")).andExpect(status().isBadRequest());. Spring raises MissingServletRequestParameterException because @RequestParam is required by default, and its default handling maps that exception to 400. ApiExceptionHandler does not handle this exception, so Spring's default response is used.