本文共 1096 字,大约阅读时间需要 3 分钟。
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方法来对其他测试需要的资源进行管理。
转载地址:http://wfkkb.baihongyu.com/