单元测试之TestNG与spring集成

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测试

3.TestNG三测试方法

评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值