Quick revision
The short answer
We send the request with mockMvc.perform(post("/orders").contentType(MediaType.APPLICATION_JSON).content(json)) and chain andExpect(status().isCreated()), andExpect(header().exists("Location")) and andExpect(jsonPath("$.id").exists()). For validation, we post an invalid body and expect status().isBadRequest() plus the problem detail fields. MockMvcTester from Spring Framework 6.2 offers the same checks with AssertJ, and in both cases no server starts.
What to remember
In this answer, we wrote a @WebMvcTest for POST /orders that sends JSON with post(), contentType() and content(), and checks 201, the Location header and JSON fields with jsonPath. We wrote a second test that posts an invalid body and expects 400 with a problem detail and no call to the service, rewrote the success test with MockMvcTester, and noted that MockMvc applies filters but not container behaviour such as error pages.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
We send the request with mockMvc.perform(post("/orders").contentType(MediaType.APPLICATION_JSON).content(json)) and chain andExpect(status().isCreated()), andExpect(header().exists("Location")) and andExpect(jsonPath("$.id").exists()). For validation, we post an invalid body and expect status().isBadRequest() plus the problem detail fields. MockMvcTester from Spring Framework 6.2 offers the same checks with AssertJ, and in both cases no server starts.
Why this question is asked
A create endpoint is where API contracts most often go wrong: the wrong status code, a missing Location header, or validation that silently accepts bad input. A MockMvc test pins all three down in milliseconds. Interviewers ask candidates to write one to see whether they know the request builders and result matchers, and whether they think about the failure case, not only the happy path. In this answer, we will look at the controller under test, write the success test line by line, write the validation test, try the AssertJ style with MockMvcTester, and note what MockMvc does not cover.
1The Controller Under Test
Our endpoint accepts an order, validates it, saves it through a service and returns 201 Created with a Location header pointing at the new resource and the order as JSON. Validation uses Jakarta Bean Validation annotations on a record, with @Valid on the parameter.
When validation fails, Spring throws MethodArgumentNotValidException before the method runs. With spring.mvc.problemdetails.enabled=true, or a @ControllerAdvice extending ResponseEntityExceptionHandler, the response is a 400 with an RFC 9457 problem detail body, JSON with fields such as type, title, status and detail.
2Testing the Successful Create
We use @WebMvcTest so only the web layer starts, mock the service, and send JSON. Each andExpect checks one part of the response.
Notice that we set the content type explicitly; without it the controller would answer 415 Unsupported Media Type. jsonPath uses JsonPath expressions, where $ is the root of the response body, so $.id is the id field. Checking the exact Location value catches a common mistake, building the URI from the wrong path.
3Testing Validation Returning 400
For the failure case we send a body that breaks both rules: a blank customer and a quantity of zero. We expect 400 and a problem detail, and we check that the service was never called.
7 messages in order. Play them, or step through them one at a time.
The controller method never runs; the exception is turned into a 400 response by Spring MVC.
The last line matters as much as the status: it proves that invalid input never reached the business logic. If the team adds field errors to the problem detail through its own @ControllerAdvice, we also assert them, for example that the errors mention customer and quantity, because clients depend on that shape.
4The Same Test With MockMvcTester
Spring Framework 6.2 added MockMvcTester, which wraps MockMvc in AssertJ assertions and needs no checked exceptions or static matcher imports. Spring Boot provides it as a bean in @WebMvcTest when AssertJ is on the classpath; check your version.
Which style to use is mostly team preference; MockMvcTester reads naturally for teams already on AssertJ and gives clearer failure messages.
5What MockMvc Does Not Test
MockMvc does not start a server. Filters registered as beans are applied, but container behaviour, such as forwarding errors to the /error page, compression and connector settings, is not. An unhandled exception is thrown out of perform() instead of becoming a 500. For those concerns we add a few tests with a real server on a random port.
6Follow-up questions
Why use @WebMvcTest rather than @SpringBootTest here?
We are testing the HTTP contract of one controller: status, headers, JSON and validation. The slice starts only the web layer, runs in about a second, and a mocked service lets us control the response exactly. A full context adds startup time without adding checks for this test.
How would you test the JSON more fully?
Compare the whole body with content().json(expected), which ignores field order and, by default, extra fields. That catches renamed fields in one assertion. For strict comparison, pass true as the second argument.
Does MockMvc apply Spring Security?
In @WebMvcTest, Spring Boot builds MockMvc with the security filter chain when Spring Security is present, so an unauthenticated POST would get 401 or 403. We then add a user with @WithMockUser and a CSRF token with with(csrf()) if CSRF protection is on.
7Conclusion
In this answer, we wrote a @WebMvcTest for POST /orders that sends JSON with post(), contentType() and content(), and checks 201, the Location header and JSON fields with jsonPath. We wrote a second test that posts an invalid body and expects 400 with a problem detail and no call to the service, rewrote the success test with MockMvcTester, and noted that MockMvc applies filters but not container behaviour such as error pages.
Open with
I would use @WebMvcTest on OrderController and mock OrderService with @MockitoBean, stubbing create to return an order with id 42. Then I call mockMvc.perform with post to /orders, contentType APPLICATION_JSON and the JSON body as content.
Then, if they want more
I chain andExpect status isCreated for the 201, header exists Location, and ideally header string Location equal to http://localhost/orders/42, since MockMvc uses localhost as the host. Then jsonPath dollar dot id exists and jsonPath dollar dot customer has the value I sent.
For validation, I post a body that breaks the constraints, say a blank customer and quantity zero, expect status isBadRequest, the content type application/problem+json, and fields like status 400 and title Bad Request in the problem detail. I also verify that the service was never called, which proves bad input never reached the business logic.
On Spring Framework 6.2 or later I could write the same thing with MockMvcTester, which gives AssertJ assertions like hasStatus CREATED and bodyJson extractingPath. And I would mention that MockMvc does not start a server: filters run, but container behaviour such as error page forwarding is not tested, so a few real-server tests cover that.
About this answer
- Last updated
- 12 November 2026
- Versions it names
- Spring Framework 6
- Checked
- Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
- Where the question comes from
- Written by Scrivio for practice. It is not taken from an interview.
- Official documentation
- Spring Boot reference, Testing
Report an issue with this answer
Copy the line below and send it to the author with what you found. It carries the address of this page.
Issue with "Write a MockMvc test for a POST /orders endpoint that checks a 201 status, a Location...": https://scrivio-interview-library.netlify.app/spring-boot/spring-boot-test/d693697572/