跳到主要内容
版本:7.0.3

使用Web Mocks

Hunyuan 7b 中英对照 Working with Web Mocks

为了提供全面的Web测试支持,TestContext框架默认启用了一个ServletTestExecutionListener。在针对WebApplicationContext进行测试时,这个TestExecutionListener会在每个测试方法执行前使用Spring Web的RequestContextHolder来设置默认的线程局部状态,并根据用@WebAppConfiguration配置的基础资源路径创建一个MockHttpServletRequest、一个MockHttpServletResponse以及一个ServletWebRequestServletTestExecutionListener还确保MockHttpServletResponseServletWebRequest能够被注入到测试实例中;测试完成后,它会清理线程局部状态。

一旦为你的测试加载了WebApplicationContext,你可能会发现需要与Web模拟对象(web mocks)进行交互——例如,在调用Web组件之后设置测试 fixtures或执行断言。以下示例展示了哪些模拟对象可以自动注入到你的测试实例中。需要注意的是,WebApplicationContextMockServletContext会在整个测试套件中被缓存,而其他模拟对象则由ServletTestExecutionListener在每个测试方法中分别管理。

@SpringJUnitWebConfig
class WacTests {

@Autowired
WebApplicationContext wac; // cached

@Autowired
MockServletContext servletContext; // cached

@Autowired
MockHttpSession session;

@Autowired
MockHttpServletRequest request;

@Autowired
MockHttpServletResponse response;

@Autowired
ServletWebRequest webRequest;

//...
}