此版本仍在开发中,尚不被认为是稳定的。对于最新的稳定版本,请使用 Spring Framework 6.2.10! |
使用Web模拟
为了提供全面的 Web 测试支持,TestContext 框架有一个ServletTestExecutionListener
默认启用。当针对WebApplicationContext
这TestExecutionListener
使用 Spring Web 的RequestContextHolder
以前
每个测试方法并创建一个MockHttpServletRequest
一个MockHttpServletResponse
和
一个ServletWebRequest
基于配置的 Base 资源路径@WebAppConfiguration
.ServletTestExecutionListener
还确保MockHttpServletResponse
和ServletWebRequest
可以注入到测试实例中,
并且,一旦测试完成,它就会清理线程本地状态。
一旦你有一个WebApplicationContext
加载测试,您可能会发现
需要与 Web 模拟进行交互——例如,设置测试夹具或
调用 Web 组件后执行断言。以下示例显示了哪些
模拟可以自动连接到您的测试实例中。请注意,WebApplicationContext
和MockServletContext
都缓存在整个测试套件中,而其他模拟是
通过ServletTestExecutionListener
.
-
Java
-
Kotlin
@SpringJUnitWebConfig
class WacTests {
@Autowired
WebApplicationContext wac; // cached
@Autowired
MockServletContext servletContext; // cached
@Autowired
MockHttpSession session;
@Autowired
MockHttpServletRequest request;
@Autowired
MockHttpServletResponse response;
@Autowired
ServletWebRequest webRequest;
//...
}
@SpringJUnitWebConfig
class WacTests {
@Autowired
lateinit var wac: WebApplicationContext // cached
@Autowired
lateinit var servletContext: MockServletContext // cached
@Autowired
lateinit var session: MockHttpSession
@Autowired
lateinit var request: MockHttpServletRequest
@Autowired
lateinit var response: MockHttpServletResponse
@Autowired
lateinit var webRequest: ServletWebRequest
//...
}