使用 Web Mock
為了提供全面的 Web 測試支援,TestContext framework 預設啟用了一個 ServletTestExecutionListener
。針對 WebApplicationContext
進行測試時,這個 TestExecutionListener
在每個測試方法執行前使用 Spring Web 的 RequestContextHolder
設定預設的執行緒本地狀態,並根據透過 @WebAppConfiguration
配置的基礎資源路徑建立 MockHttpServletRequest
、MockHttpServletResponse
和 ServletWebRequest
。ServletTestExecutionListener
還確保 MockHttpServletResponse
和 ServletWebRequest
可以注入到測試例項中,並且在測試完成後清理執行緒本地狀態。
一旦為測試載入了 WebApplicationContext
,你可能需要與 Web Mock 互動 — 例如,設定測試夾具或在呼叫 Web 元件後執行斷言。下面的示例展示了哪些 Mock 可以自動裝配到測試例項中。請注意,WebApplicationContext
和 MockServletContext
在整個測試套件中都會被快取,而其他 Mock 則由 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
//...
}