使用SpringTest测试,默认情况事务是不会提交的

代码如下:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={"classpath:spring-bean.xml"})
public class DictionaryMapperTest{
	
	@Autowired
	private DictionaryItemMapper dictionaryItemMapper;
	
	
	@Test
	public void add(){
		DictionaryItem dic = new DictionaryItem();
		dic.setDicCode("0013");
		dic.setDicName("测试");
		dic.setGroupCode("001");
		dictionaryItemMapper.save(dic);
	}	
}

经过查找发现: 在上面这段示例代码中,test方法中的测试数据不会真的提交数据库,他将在test方法执行完毕后进行回滚。

如果你希望控制测试代码的事务提交,可以通过一些annotation来完成。 比如改成下面这样

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={"classpath:spring-bean.xml"})
@TransactionConfiguration(transactionManager = "txMgr", defaultRollback = true)
public class DictionaryMapperTest{
	
	@Autowired
	private DictionaryItemMapper dictionaryItemMapper;
	
	
	@Test
	public void add(){
		DictionaryItem dic = new DictionaryItem();
		dic.setDicCode("0014");
		dic.setDicName("测试");
		dic.setGroupCode("001");
		dictionaryItemMapper.save(dic);
	}	
}

 参考:http://www.iteye.com/problems/100963

你可能感兴趣的:(使用SpringTest测试,默认情况事务是不会提交的)