執行請求

本節展示瞭如何單獨使用 MockMvc 來執行請求和驗證響應。如果透過 WebTestClient 使用 MockMvc,請參閱 編寫測試 中的相應部分。

要執行使用任何 HTTP 方法的請求,如以下示例所示:

  • Java

  • Kotlin

// static import of MockMvcRequestBuilders.*

mockMvc.perform(post("/hotels/{id}", 42).accept(MediaType.APPLICATION_JSON));
import org.springframework.test.web.servlet.post

mockMvc.post("/hotels/{id}", 42) {
	accept = MediaType.APPLICATION_JSON
}

您還可以執行檔案上傳請求,這些請求內部使用 MockMultipartHttpServletRequest,因此實際上沒有對多部分請求進行解析。相反,您必須將其設定為類似於以下示例:

  • Java

  • Kotlin

mockMvc.perform(multipart("/doc").file("a1", "ABC".getBytes("UTF-8")));
import org.springframework.test.web.servlet.multipart

mockMvc.multipart("/doc") {
	file("a1", "ABC".toByteArray(charset("UTF8")))
}

您可以按 URI 模板樣式指定查詢引數,如以下示例所示:

  • Java

  • Kotlin

mockMvc.perform(get("/hotels?thing={thing}", "somewhere"));
mockMvc.get("/hotels?thing={thing}", "somewhere")

您還可以新增表示查詢引數或表單引數的 Servlet 請求引數,如以下示例所示:

  • Java

  • Kotlin

mockMvc.perform(get("/hotels").param("thing", "somewhere"));
import org.springframework.test.web.servlet.get

mockMvc.get("/hotels") {
	param("thing", "somewhere")
}

如果應用程式程式碼依賴於 Servlet 請求引數,並且不明確檢查查詢字串(通常情況下),則您使用哪種選項都無關緊要。但是請記住,透過 URI 模板提供的查詢引數是經過解碼的,而透過 param(…​) 方法提供的請求引數則應假定已解碼。

在大多數情況下,最好將上下文路徑和 Servlet 路徑排除在請求 URI 之外。如果必須使用完整的請求 URI 進行測試,請務必相應地設定 contextPathservletPath,以便請求對映正常工作,如以下示例所示:

  • Java

  • Kotlin

mockMvc.perform(get("/app/main/hotels/{id}").contextPath("/app").servletPath("/main"))
import org.springframework.test.web.servlet.get

mockMvc.get("/app/main/hotels/{id}") {
	contextPath = "/app"
	servletPath = "/main"
}

在前面的示例中,在每個執行的請求中設定 contextPathservletPath 會很麻煩。相反,您可以設定預設請求屬性,如以下示例所示:

  • Java

  • Kotlin

class MyWebTests {

	MockMvc mockMvc;

	@BeforeEach
	void setup() {
		mockMvc = standaloneSetup(new AccountController())
			.defaultRequest(get("/")
			.contextPath("/app").servletPath("/main")
			.accept(MediaType.APPLICATION_JSON)).build();
	}
}
class MyWebTests {

	lateinit var mockMvc: MockMvc

	@BeforeEach
	fun setup() {
		mockMvc = standaloneSetup(AccountController())
			.defaultRequest<StandaloneMockMvcBuilder>(get("/")
			.contextPath("/app").servletPath("/main")
			.accept(MediaType.APPLICATION_JSON)).build()
	}
}

上述屬性會影響透過 MockMvc 例項執行的每個請求。如果某個給定請求上也指定了相同的屬性,它會覆蓋預設值。這就是為什麼預設請求中的 HTTP 方法和 URI 無關緊要的原因,因為它們必須在每個請求中指定。

© . This site is unofficial and not affiliated with VMware.