Working with Web Mocks
为了提供全面的 Web 测试支持,TestContext 框架有一个 ServletTestExecutionListener
,它默认启用。当针对 WebApplicationContext
进行测试时,此 TestExecutionListener
使用 Spring Web 的 RequestContextHolder
在每个测试方法之前设置默认线程局部状态,并创建 MockHttpServletRequest
、MockHttpServletResponse
和 ServletWebRequest
,这些基于使用 @WebAppConfiguration
配置的基本资源路径。ServletTestExecutionListener
还确保 MockHttpServletResponse
和 ServletWebRequest
可以注入到测试实例中,并且一旦测试完成,它将清理线程局部状态。
To provide comprehensive web testing support, the TestContext framework has a
ServletTestExecutionListener
that is enabled by default. When testing against a
WebApplicationContext
, this TestExecutionListener
sets up default thread-local state by using Spring Web’s RequestContextHolder
before
each test method and creates a MockHttpServletRequest
, a MockHttpServletResponse
, and
a ServletWebRequest
based on the base resource path configured with
@WebAppConfiguration
. ServletTestExecutionListener
also ensures that the
MockHttpServletResponse
and ServletWebRequest
can be injected into the test instance,
and, once the test is complete, it cleans up thread-local state.
一旦为你的测试加载了一个 WebApplicationContext
,你可能会发现需要与 web mock 进行交互——例如,设置你的测试固定装置或在调用你的 web 组件后执行断言。以下示例展示了哪些 mock 可以自动注入到你的测试实例中。请注意,WebApplicationContext
和 MockServletContext
都跨测试套件缓存,而其他 mock 由 ServletTestExecutionListener
按测试方法管理。
Once you have a WebApplicationContext
loaded for your test, you might find that you
need to interact with the web mocks — for example, to set up your test fixture or to
perform assertions after invoking your web component. The following example shows which
mocks can be autowired into your test instance. Note that the WebApplicationContext
and
MockServletContext
are both cached across the test suite, whereas the other mocks are
managed per test method by the ServletTestExecutionListener
.
-
Injecting 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
//...
}