I have some unit tests that use JUnit and Spring to test a simple DAO.
My understanding is that when I mark a class as @Transactional, the @BeforeTransaction and @AfterTransaction methods should run before and after my @Test methods. However, these methods are not being fired at all. I don't see any output from the before & after methods, and if I add breakpoints they don't get hit.
Any idea what I'm doing wrong here?
@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);
}
}
Output:
Hello from testInsert!
Hello from testRetrieve!
EDIT: Fixed this by adding this bean to my configuration.
@Bean
public PlatformTransactionManager dataSourceTransactionManager() {
DataSourceTransactionManager txMgr = new DataSourceTransactionManager();
txMgr.setDataSource(dataSource);
return txMgr;
}
http://docs.spring.io/spring/docs/current/spring-framework-reference/html/testing.html