使用 Web 模拟对象
为了提供全面的 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
//...
}