使用Web Mocks
为了提供全面的Web测试支持,TestContext框架默认启用了ServletTestExecutionListener。当针对WebApplicationContext进行测试时,这个TestExecutionListener会在每个测试方法之前通过使用Spring Web的RequestContextHolder来设置默认的线程本地状态,并基于使用@WebAppConfiguration配置的基本资源路径创建MockHttpServletRequest、MockHttpServletResponse和ServletWebRequest。 ServletTestExecutionListener还确保MockHttpServletResponse和ServletWebRequest可以被注入到测试实例中,并在测试完成后清理线程本地状态。
一旦为您的测试加载了WebApplicationContext,您可能会发现需要与Web mocks进行交互,例如设置测试夹具或在调用Web组件后执行断言。以下示例显示了哪些mocks可以自动装配到您的测试实例中。请注意,WebApplicationContext和MockServletContext都会在整个测试套件中被缓存,而其他mocks则由ServletTestExecutionListener按测试方法进行管理。
-
注入mocks
-
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
//...
}