Setup Features
无论你使用哪个 MockMvc 构建器,所有 MockMvcBuilder
实现都提供了一些常见且非常有用的功能。例如,你可以声明所有请求的 Accept
标头并期望所有响应中的状态为 200 以及 Content-Type
标头,如下所示:
No matter which MockMvc builder you use, all MockMvcBuilder
implementations provide
some common and very useful features. For example, you can declare an Accept
header for
all requests and expect a status of 200 as well as a Content-Type
header in all
responses, as follows:
-
Java
-
Kotlin
// static import of MockMvcBuilders.standaloneSetup
MockMvc mockMvc = standaloneSetup(new MusicController())
.defaultRequest(get("/").accept(MediaType.APPLICATION_JSON))
.alwaysExpect(status().isOk())
.alwaysExpect(content().contentType("application/json;charset=UTF-8"))
.build();
// Not possible in Kotlin until {kotlin-issues}/KT-22208 is fixed
此外,第三方框架(和应用程序)可以通过预打包设置指令,如 MockMvcConfigurer
中的指令。Spring 框架有一个内置于实现,有助于保存并跨请求重复使用 HTTP 会话。你可以按以下方式使用它:
In addition, third-party frameworks (and applications) can pre-package setup
instructions, such as those in a MockMvcConfigurer
. The Spring Framework has one such
built-in implementation that helps to save and re-use the HTTP session across requests.
You can use it as follows:
-
Java
-
Kotlin
// static import of SharedHttpSessionConfigurer.sharedHttpSession
MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new TestController())
.apply(sharedHttpSession())
.build();
// Use mockMvc to perform requests...
// Not possible in Kotlin until {kotlin-issues}/KT-22208 is fixed
请参阅 javadoc ConfigurableMockMvcBuilder
以获取所有 MockMvc 构建器功能的列表,或使用 IDE 探索可用选项。
See the javadoc for
ConfigurableMockMvcBuilder
for a list of all MockMvc builder features or use the IDE to explore the available options.