使用 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
//...
}