spring整合testng單元測試
阿新 • • 發佈:2018-11-04
Spring整合testng單元測試有兩種方式,一種是引入spring-test等相關包,另一種是隻使用testng。本文只介紹第二種方式,此方式的優點是不需要引入額外的spring-test包,缺點是需要手動呼叫方法來獲得例項。
import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import org.testng.annotations.AfterSuite; import org.testng.annotations.BeforeSuite; public abstract class BaseTest { protected ApplicationContext context; protected String springXmlpath; protected String getSpringXmlpath() { return "springConfig.xml"; } /** * 子類重寫後可在載入完xml檔案後,進行其他的初始化操作 */ protected void init() { } @BeforeSuite public void setUp() throws Exception { springXmlpath = getSpringXmlpath(); if (springXmlpath != null) { context = new ClassPathXmlApplicationContext(springXmlpath.split("[;\\s]+")); } else { System.err.println("spring xml path can not be null"); System.exit(-1); } init(); } @AfterSuite public void tearDown() throws Exception { destroy(); } /** * 子類重寫後可在銷燬context例項後,進行其他資源的釋放操作 */ protected void destroy() { } }
其他測試類繼承BaseTest即可,可以通過重寫getSpringXmlpath方法來設定要載入的xml檔案,通過重寫init與destroy方法來對其他測試需要的資源進行管理。