Spring2.5以后,就开始支持TestNG了,org.springframework.test.context.testng包为基于TestNG的测试用例提供了支持类。
1、AbstractTestNGSpringContextTests
对集成了Spring TestContext Framework与TestNG环境中的ApplicationContext测试支持的基础测试类进行了抽象。当你继承AbstractTestNGSpringContextTests时,就可以访问到下列protected的成员变量:applicationContext:使用它进行显式的bean查找或 者测试整个上下文的状态。
2、AbstractTransactionalTestNGSpringContextTests
继承该类的测试用例在spring管理的事务中进行,测试完后对数据库的记录不会造成任何影响。你对数据库进行一些操作后,它会自动把数据库回滚,这样就保证了你的测试对于环境没有任何影响。对为JDBC访问增加便捷功能的AbstractTestNGSpringContextTests的事务扩展进行抽象。需要在ApplicationContext中定义一个javax.sql.DataSource bean和一个PlatformTransactionManager bean。当你继承AbstractTransactionalTestNGSpringContextTests类时,就可以访问下列protected的成员变量:applicationContext和simpleJdbcTemplate
在测试类上使用 @TestExecutionListeners 注释标签,可以引入的监听器包括
DependencyInjectionTestExecutionListener:使得测试类拥有依赖注入特性DirtiesContextTestExecutionListener:使得测试类拥有更新 applicationContext 能力
TransactionalTestExecutionListener:使得测试类拥有自动的事务管理能力
package cn.slimsmart.unit.test.demo.testng;
import static org.junit.Assert.assertTrue;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.testng.AbstractTestNGSpringContextTests;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import cn.slimsmart.unit.test.demo.junit.AddService;
@ContextConfiguration(locations = { "classpath*:/applicationContext.xml" })
public class SpringTestNG extends AbstractTestNGSpringContextTests {
@Autowired
private AddService addService;
@BeforeClass
public void setUp(){
System.out.println("初始化");
}
@Test
public void testAdd() {
assertTrue(addService.add(1, 1) == 2);
}
@AfterClass
public void destroy() {
System.out.println("退出,资源释放");
}
}
testng.xml配置:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" >
<suite name="Suite">
<test name="test">
<classes>
<class name="cn.slimsmart.unit.test.demo.testng.TestNGTest"/>
</classes>
</test>
<test name="test_spring">
<classes>
<class name="cn.slimsmart.unit.test.demo.testng.SpringTestNG">
<methods>
<include name="testAdd" />
</methods>
</class>
</classes>
</test>
</suite>
如果需要测试多个类,在testng.xml文件中添加此XML文件的路径:
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="common-service" verbose="1">
<suite-file path="../unit-test/src/test/testng.counselServiceTest.xml" />
<suite-file path="../unit-test/src/test/testng.perturbServiceTest.xml" />
</suite-files>
</suite>
参考文章:
1.TestNG
2.TestNG测试