Spring MVC / HTTP

MockMvc.perform

Execute a simulated MVC request and assert response properties, without a listening socket. Boot 4.0.10 companion project; source-reviewed, not executed.

Formal Syntax & Structure

java syntaxjava
mvc.perform(get("/api/v1/items/A1"))

Working Example

Example Snippetjava
package example.inventory;import org.junit.jupiter.api.Test;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.boot.test.context.SpringBootTest;import org.springframework.boot.webmvc.test.autoconfigure.AutoConfigureMockMvc;import org.springframework.test.web.servlet.MockMvc;import org.springframework.test.annotation.DirtiesContext;import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;@SpringBootTest@AutoConfigureMockMvc@DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_EACH_TEST_METHOD)class InventoryContractTest {    @Autowired MockMvc mvc;    @Test void readAndPage() throws Exception {        mvc.perform(get("/api/v1/items/A1").accept("application/json"))            .andExpect(status().isOk()).andExpect(content().contentTypeCompatibleWith("application/json"))            .andExpect(jsonPath("$.sku").value("A1")).andExpect(jsonPath("$.internalNote").doesNotExist());        mvc.perform(get("/api/v1/items?size=2&sort=name"))            .andExpect(status().isOk()).andExpect(jsonPath("$.items[1].sku").value("C3"));    }    @Test void errors() throws Exception {        mvc.perform(get("/api/v1/items/Z9")).andExpect(status().isNotFound())            .andExpect(content().contentTypeCompatibleWith("application/problem+json"))            .andExpect(jsonPath("$.status").value(404));        mvc.perform(post("/api/v1/items").contentType("application/json").content("{\"sku\":\"Z8\",\"name\":\"Pen\"}"))            .andExpect(status().isBadRequest());        mvc.perform(get("/api/v1/items?size=101")).andExpect(status().isBadRequest());        mvc.perform(post("/api/v1/items").contentType("text/plain").content("bad")).andExpect(status().isUnsupportedMediaType());        mvc.perform(get("/api/v1/items/A1").accept("image/png")).andExpect(status().isNotAcceptable());    }    @Test void createThenConflict() throws Exception {        String body = "{\"sku\":\"D4\",\"name\":\"Eraser\",\"quantity\":3}";        mvc.perform(post("/api/v1/items").contentType("application/json").content(body))            .andExpect(status().isCreated()).andExpect(header().string("Location", "/api/v1/items/D4"));        mvc.perform(post("/api/v1/items").contentType("application/json").content(body))            .andExpect(status().isConflict()).andExpect(jsonPath("$.status").value(409));    }}
Java Reference