Configuring MockMvc
有两种方式可以设置 MockMvc。一是直接指向你想要测试的 controller 并对 Spring MVC 基础架构进行编程配置。另一种方法是使用其中包含 Spring MVC 和 controller 基础架构的 Spring 配置进行设置。
MockMvc can be setup in one of two ways. One is to point directly to the controllers you want to test and programmatically configure Spring MVC infrastructure. The second is to point to Spring configuration with Spring MVC and controller infrastructure in it.
有关这两种模式的比较,请检查 Setup Options。 |
For a comparison of those two modes, check Setup Options. |
要设置 MockMvc 以测试特定的 controller,请使用以下方法:
To set up MockMvc for testing a specific controller, use the following:
-
Java
-
Kotlin
class MyWebTests {
MockMvc mockMvc;
@BeforeEach
void setup() {
this.mockMvc = MockMvcBuilders.standaloneSetup(new AccountController()).build();
}
// ...
}
class MyWebTests {
lateinit var mockMvc : MockMvc
@BeforeEach
fun setup() {
mockMvc = MockMvcBuilders.standaloneSetup(AccountController()).build()
}
// ...
}
您还可以使用此设置通过 WebTestClient 进行测试,后者委派给上面显示的同一生成器。
Or you can also use this setup when testing through the WebTestClient which delegates to the same builder as shown above.
要通过 Spring 配置设置 MockMvc,请使用以下方法:
To set up MockMvc through Spring configuration, use the following:
-
Java
-
Kotlin
@SpringJUnitWebConfig(locations = "my-servlet-context.xml")
class MyWebTests {
MockMvc mockMvc;
@BeforeEach
void setup(WebApplicationContext wac) {
this.mockMvc = MockMvcBuilders.webAppContextSetup(wac).build();
}
// ...
}
@SpringJUnitWebConfig(locations = ["my-servlet-context.xml"])
class MyWebTests {
lateinit var mockMvc: MockMvc
@BeforeEach
fun setup(wac: WebApplicationContext) {
mockMvc = MockMvcBuilders.webAppContextSetup(wac).build()
}
// ...
}
您还可以使用此设置通过 WebTestClient 进行测试,后者委派给上面显示的同一生成器。
Or you can also use this setup when testing through the WebTestClient which delegates to the same builder as shown above.