我有一些单元测试使用JUnit和Spring来测试一个简单的DAO。
我的理解是,当我将一个类标记为@Transactional时,@ BeeTransaction和@AfterTransaction方法应该在我的@Test方法之前和之后运行。但是,这些方法根本没有被解雇。我没有看到之前和之前的任何输出。在方法之后,如果我添加断点,它们就不会被击中。
知道我在这里做错了吗?
@RunWith(SpringJUnit4ClassRunner.class)
@TestPropertySource("/app.properties")
@Transactional
@ContextConfiguration(classes={TestDataSourceConfiguration.class, GeneralConfiguration.class}, loader=AnnotationConfigContextLoader.class)
public class TestBreadDAO {
@Autowired
private BreadDAO breadDAO;
@BeforeTransaction
public void beforeTransaction() {
System.out.println("Hello from beforeTransaction!");
}
@Test
public void testRetrieve() throws SQLException {
System.out.println("Hello from testRetrieve!");
Bread bread = breadDAO.retrieveBreadById("1");
Assert.assertTrue(bread != null);
Assert.assertTrue(bread.getBreadId().equals("1"));
Assert.assertTrue(bread.getSesameSeeds() == 41000);
Assert.assertTrue(bread.getOats() == 100000);
}
@Test
public void testInsert() throws SQLException {
System.out.println("Hello from testInsert!");
Bread bread = new Bread();
bread.setBreadId("20");
bread.setSesameSeeds(15000);
bread.setOats(30000);
breadDAO.insertBread(Bread);
Bread bread2 = breadDAO.retrieveBreadById("20");
Assert.assertTrue(bread.getBreadId().equals(bread2.getBreadId()));
Assert.assertTrue(bread.getSesameSeeds() == bread2.getSesameSeeds());
Assert.assertTrue(bread.getOats() == bread2.getOats());
}
@AfterTransaction
public void afterTransaction() {
System.out.println("Hello from afterTransaction!");
Bread bread = breadDAO.retrieveBreadById("20");
Assert.assertTrue(bread == null);
}
}
输出:
Hello from testInsert!
Hello from testRetrieve!
编辑:通过将此bean添加到我的配置中来解决此问题。
@Bean
public PlatformTransactionManager dataSourceTransactionManager() {
DataSourceTransactionManager txMgr = new DataSourceTransactionManager();
txMgr.setDataSource(dataSource);
return txMgr;
}
答案 0 :(得分:1)
要启用事务支持,必须在ApplicationContext中配置PlatformTransactionManager bean
http://docs.spring.io/spring/docs/current/spring-framework-reference/html/testing.html