Spring 提供豐富的測試支持體系,覆蓋單元級 Mock、集成級上下文緩存、事務性數據庫測試三大場景。本文系統梳理核心類層次、最佳實踐與常見坑點。
位於 org.springframework.mock.*,核心類:
MockHttpServletRequest:模擬 HTTP 請求,addParameter、setMethod 等極便利。MockHttpServletResponse:捕獲響應內容、狀態碼、Header。MockHttpSession、MockServletConfig、MockFilterConfig、MockPageContext(可測試預編譯 JSP)。DelegatingServletInputStream/OutputStream:攔截流內容分析。示例:
MockHttpServletRequest req = new MockHttpServletRequest("POST", "/index.do");
req.addParameter("username", "name");
均在 org.springframework.test 包,繼承關係:
getConfigLocations() 返回配置路徑數組。protected JdbcTemplate jdbcTemplate 直接操作數據庫,適合持久層測試。// 基於 classpath(文件需在 WEB-INF/classes 或源碼目錄)
public String[] getConfigLocations() {
return new String[] {"applicationContext.xml", "hibernate-context.xml"};
}
// 基於文件系統相對路徑(相對於專案根目錄)
public String[] getConfigLocations() {
return new String[] {"file:WebContent/WEB-INF/applicationContext.xml"};
}
onSetUp() 中顯式 applicationContext.getBean("beanName")。AbstractSpringContextTests。框架按 getConfigLocations() 返回數組緩存 Context,大項目啟動一次可節省 10-20 秒。若測試修改了 Bean 定義/狀態,調用 setDirty() 強制下一測試重新加載。
public class ProductManagerTest extends AbstractTransactionalDataSourceSpringContextTests {
private ProductManager productManager;
public String[] getConfigLocations() {
return new String[] {"file:WebContent/WEB-INF/applicationContext.xml"};
}
public void setProductManager(ProductManager pm) { this.productManager = pm; }
public void testGetProduct() {
assertEquals("tomson", productManager.getProductByName("tomson").getName());
}
}
jdbcTemplate 僅在 AbstractTransactionalDataSourceSpringContextTests 及其子類可用。@RunWith(SpringJUnit4ClassRunner.class) + @ContextConfiguration 註解風格,舊基類已標註 Deprecated。