Sub topic 13
Trying the endpoints with curl and MockMvc
This chapter checks the endpoints from the earlier chapters in two ways. You will call a running application with curl, then write automated tests with MockMvc. It assumes you have the BookController, CreateBookRequest, and ApiExceptionHandler classes from the previous chapters. It also assumes you know basic JUnit 5 and the Mockito when(...) style, and that your project includes spring-boot-starter-test.
The tests assume Book is a record with the fields Long id, String title, String author, and int pages. Adjust the constructor calls if yours differs.
Two ways to exercise an endpoint
curl sends a real HTTP request to a running server. It is quick, needs no code, and shows exactly what a client sees. The result disappears when you close the terminal, so it is not a regression check.
MockMvc builds a request in memory and passes it to Spring MVC's DispatcherServlet, without opening a socket. Path matching, argument binding, validation, and your @RestControllerAdvice all run. The servlet container, ports, and TLS do not. That makes a MockMvc test fast and repeatable, and you can run it in a build.
Calling the endpoints with curl
Start the application, for example with ./mvnw spring-boot:run. It listens on port 8080 unless you changed server.port.
Path variable
curl -i http://localhost:8080/api/books/42The -i flag prints the status line and response headers before the body. Without it you see only the body and cannot tell a 200 from a 404 unless the body says so.
Query parameters
A & is a shell operator, so always quote URLs that contain one.
curl -i "http://localhost:8080/api/books?author=Le%20Guin&page=0&size=10"Writing %20 by hand is easy to get wrong. With -G, curl moves -d and --data-urlencode values into the query string and encodes them for you:
curl -i -G http://localhost:8080/api/books \
--data-urlencode "author=Le Guin" \
-d page=0 \
-d size=10To check the defaults, send no parameters. The controller should then use page=0 and size=20:
curl -i http://localhost:8080/api/booksJSON body
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}'A successful call returns 201 Created and a Location header such as http://localhost:8080/api/books/1. Recent curl versions (7.82 and later) accept --json, which sets the Content-Type and Accept headers for you:
curl -i --json '{"title":"A Wizard of Earthsea","author":"Ursula K. Le Guin","pages":183}' \
http://localhost:8080/api/booksProvoking the error paths
Happy paths prove little. Send bad input on purpose and confirm that you get a 400 and not a 500.
# Type mismatch: "abc" is not a Long
curl -i http://localhost:8080/api/books/abc
# Type mismatch: not an ISO date
curl -i "http://localhost:8080/api/books/published?since=yesterday"
# Missing required parameter "since"
curl -i http://localhost:8080/api/books/published
# Validation failure: blank title, negative pages
curl -i -X POST http://localhost:8080/api/books \
-H "Content-Type: application/json" \
-d '{"title":"","author":"Someone","pages":-5}'
# Malformed JSON
curl -i -X POST http://localhost:8080/api/books \
-H "Content-Type: application/json" \
-d '{"title":'
# No Content-Type header
curl -i -X POST http://localhost:8080/api/books -d '{"title":"x"}'The expected results are:
| Request | Status | Why |
|---|---|---|
| `/api/books/abc` | 400 | `MethodArgumentTypeMismatchException`, handled by `ApiExceptionHandler` |
| `published?since=yesterday` | 400 | The date cannot be parsed, so the same exception |
| `published` without `since` | 400 | `MissingServletRequestParameterException`, handled by Spring's default resolver |
| Blank title, negative pages | 400 | `MethodArgumentNotValidException`, with an `errors` map |
| Truncated JSON | 400 | `HttpMessageNotReadableException` from Jackson |
| No `Content-Type` | 415 | No message converter matches the media type |
The last row is a common surprise. A POST that is missing the Content-Type: application/json header is rejected with 415 Unsupported Media Type before your method runs. Without -H, curl's -d sends application/x-www-form-urlencoded, so the 415 appears even when the JSON itself is fine.
The validation failure returns a body like this, with Content-Type: application/problem+json:
{
"type": "about:blank",
"title": "Bad Request",
"status": 400,
"detail": "Request body failed validation",
"instance": "/api/books",
"errors": {
"title": "must not be blank",
"pages": "must be greater than 0"
}
}Testing with MockMvc
Setting up a web-layer test
@WebMvcTest starts only the web layer. It loads the named controller, @ControllerAdvice classes such as ApiExceptionHandler, and the JSON and conversion infrastructure. It does not load @Service or repository beans, so you must supply BookService as a mock. That keeps the tests focused on binding, validation, and error mapping.
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
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.time.LocalDate;
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 mockMvc;
@MockitoBean
BookService service;
private static final Book DUNE = new Book(1L, "Dune", "Frank Herbert", 412);
@Test
void getByIdBindsPathVariable() throws Exception {
when(service.get(42L)).thenReturn(DUNE);
mockMvc.perform(get("/api/books/{id}", 42))
.andExpect(status().isOk())
.andExpect(jsonPath("$.title").value("Dune"));
}
@Test
void nonNumericIdIsBadRequest() throws Exception {
mockMvc.perform(get("/api/books/abc"))
.andExpect(status().isBadRequest())
.andExpect(jsonPath("$.detail").value("Invalid value for parameter 'id'"));
verifyNoInteractions(service);
}
@Test
void searchBindsQueryParameters() throws Exception {
when(service.search("Le Guin", 0, 10)).thenReturn(List.of(DUNE));
mockMvc.perform(get("/api/books")
.param("author", "Le Guin")
.param("page", "0")
.param("size", "10"))
.andExpect(status().isOk())
.andExpect(jsonPath("$[0].title").value("Dune"));
}
@Test
void searchUsesDefaultsWhenParametersAreAbsent() throws Exception {
when(service.search(null, 0, 20)).thenReturn(List.of());
mockMvc.perform(get("/api/books"))
.andExpect(status().isOk());
verify(service).search(null, 0, 20);
}
@Test
void publishedSinceParsesIsoDate() throws Exception {
when(service.publishedSince(LocalDate.of(2024, 5, 1))).thenReturn(List.of(DUNE));
mockMvc.perform(get("/api/books/published").param("since", "2024-05-01"))
.andExpect(status().isOk());
}
@Test
void missingRequiredParameterIsBadRequest() throws Exception {
mockMvc.perform(get("/api/books/published"))
.andExpect(status().isBadRequest());
}
@Test
void createReturns201AndLocation() throws Exception {
when(service.create(any(CreateBookRequest.class))).thenReturn(DUNE);
mockMvc.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/1"))
.andExpect(jsonPath("$.id").value(1));
}
@Test
void invalidBodyReturnsFieldErrors() throws Exception {
mockMvc.perform(post("/api/books")
.contentType(MediaType.APPLICATION_JSON)
.content("""
{"title":"","author":"Someone","pages":-5}
"""))
.andExpect(status().isBadRequest())
.andExpect(jsonPath("$.errors.title").exists())
.andExpect(jsonPath("$.errors.pages").exists());
verifyNoInteractions(service);
}
@Test
void missingContentTypeIsUnsupportedMediaType() throws Exception {
mockMvc.perform(post("/api/books").content("{\"title\":\"x\"}"))
.andExpect(status().isUnsupportedMediaType());
}
}This sample targets Spring Boot 3.4 or later, where @MockitoBean is available. On earlier 3.x versions, use @MockBean from org.springframework.boot.test.mock.mockito instead. The rest of the test is unchanged.
What these tests prove
get("/api/books/{id}", 42)expands the URI template. Passing42as anintis fine, because it is only turned into text for the URL..param(...)takes decoded values. Write"Le Guin", not"Le%20Guin". Passing the encoded form would send a literal%20in the value.verifyNoInteractions(service)in the failure tests proves that binding or validation rejected the request before your business code ran. A 400 alone does not prove that.- In the defaults test,
verify(service).search(null, 0, 20)shows what Spring actually passed. An absent optionalStringisnull, and thedefaultValuestrings were converted toint. .contentType(MediaType.APPLICATION_JSON)is the MockMvc counterpart of curl's-H. Leave it out and you reproduce the 415 case.
Two habits that save time
Add .andDo(print()) to a failing test to dump the request, the handler that matched, any resolved exception, and the response. The "Resolved Exception" section names the exact exception type, which tells you which handler to write or fix.
When the JSON gets longer, build it with ObjectMapper instead of a text block. Inject it with @Autowired ObjectMapper objectMapper and call objectMapper.writeValueAsString(new CreateBookRequest("Dune", "Frank Herbert", 412)). Renaming a record component then breaks the compile, not just the test run.
Choosing a tool
| Need | Best choice |
|---|---|
| Look at the raw response while developing | curl with `-i` |
| Repeatable check of binding, validation, and error format | `@WebMvcTest` with MockMvc |
| Check the controller together with real services and a database | `@SpringBootTest` with MockMvc or a real port |
| Check the encoded URL a real client would send | curl, preferably with `-G --data-urlencode` |
A practical order is to try an endpoint with curl as you write it. Once its behavior is settled, capture that behavior in a MockMvc test, including the 400 and 415 cases.
Exercise
A test posts {"title":"Dune","author":"Frank Herbert","pages":412} to /api/books with MockMvc and gets a 415 response. The JSON is valid and the controller works with curl. What is missing from the test, and how would you confirm the fix?
Show answer
The request has no .contentType(MediaType.APPLICATION_JSON), so no message converter matches and Spring rejects it with 415 before the controller runs. Add the content type to the request builder. Then the test should return 201, and you can assert the Location header and the $.id value.
Exercise
Write a MockMvc test that proves GET /api/books?size=abc returns 400 and never calls the service. Which exception does Spring raise, and which class turns it into the response?
Show answer
Use mockMvc.perform(get("/api/books").param("size", "abc")).andExpect(status().isBadRequest()); followed by verifyNoInteractions(service);. Spring raises MethodArgumentTypeMismatchException because "abc" cannot be converted to int. The handleTypeMismatch method in ApiExceptionHandler turns it into a ProblemDetail with status 400.
Exercise
Using curl, how do you send the query author=Le Guin&page=0 without hand-encoding the space, and why is the URL quoted in the other form?
Show answer
Run curl -i -G http://localhost:8080/api/books --data-urlencode "author=Le Guin" -d page=0. The -G flag puts the data in the query string and --data-urlencode encodes the space as %20. When you write the URL yourself, quote it because an unquoted & makes the shell run the command in the background and cut the URL short.