Spring+Junit单元测试

    1,建立测试的BaseTest类,供子类继承配置信息

package com.jiekuaida.service.impl;

import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.transaction.TransactionConfiguration;
import org.springframework.transaction.annotation.Transactional;

//启动 Spring 对测试类的支持
@RunWith(SpringJUnit4ClassRunner.class)
// 指定 Spring 配置文件或者配置类的位置
@ContextConfiguration(locations = {
		"/com/jiekuaida/config/spring/applicationContext-aop.xml",
		"/com/jiekuaida/config/spring/applicationContext-basic.xml",
		"/com/jiekuaida/config/spring/applicationContext-component.xml",
		"/com/jiekuaida/config/spring/applicationContext-dao.xml",
		"/com/jiekuaida/config/spring/applicationContext-memcacahed.xml",
		"/com/jiekuaida/config/spring/applicationContext-security.xml",
		"/com/jiekuaida/config/spring/applicationContext-service.xml"})
// 启用自动的事务管理
@Transactional
// 指定 transactionManager属性名称, 缺省为transactionManager
// 还可以指定 defaultRollback 属性,缺省为 true
@TransactionConfiguration(transactionManager = "txManager", defaultRollback = true)
public class BaseTest {
}
 

    2,子测试类

public class OwnerTest extends BaseTest {
        //直接注入,无需Spring配置自动扫描
	@Resource
	private OwnerDao ownerDao;

	@Test
	public void testOwner() throws Exception {
		System.out.println(ownerDao.findOwnerByJKDUserId(1));
	}
}

 

你可能感兴趣的:(java,spring,JUnit,单元测试)