使用 Web Mocks
为了提供全面的 Web 测试支持,TestContext 框架默认启用了一个 ServletTestExecutionListener
。当针对 WebApplicationContext
进行测试时,这个 TestExecutionListener 会在每个测试方法执行之前,使用 Spring Web 的 RequestContextHolder
设置默认的线程本地状态,并根据使用 @WebAppConfiguration
配置的基础资源路径创建一个 MockHttpServletRequest
、一个 MockHttpServletResponse
和一个 ServletWebRequest
。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
//...
}