升级Spring4.2.2 后用JUnit4 测试事物提交发现无法插入数据,网上参考了些例子才发现,Spring4.2.2的测试用例类不可继承“AbstractTransactionalJUnit4SpringContextTests”。
这里给一个测试用例的父类,继承之即可:
package cn.jaakan.test.util;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath*:/spring-context.xml")
/*
* Spring4.2.2 JUnit4 事物提交需要去掉 "extends AbstractTransactionalJUnit4SpringContextTests"
*/
public abstract class BaseTestCase{
}
使用的时候:
package cn.jaakan.test.core;
import javax.annotation.Resource;
import org.junit.Test;
import org.springframework.test.annotation.Rollback;
import cn.jaakan.service.core.DeptService;
import cn.jaakan.test.util.BaseTestCase;
public class DeptTest extends BaseTestCase {
@Resource private DeptService deptService;
@Test
@Rollback(true)
public void add(){
try {
deptService.create("dept1", "部门1", 1, null, "");
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
public DeptService getDeptService() {
return deptService;
}
public void setDeptService(DeptService deptService) {
this.deptService = deptService;
}
}