使用 Web Mock
为提供全面的 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
//...
}