I'm trying to use SpringJunit4ClassRunner
to test my DAO classes without leaving data behind when I've finished, through the use of the @Transactional
annotation. My DAO class contains (stripped down):
@Repository
public class IdsFunctionJpaController {
@PersistenceContext
EntityManager em;
public void save(IdsFunction function) {
if (function.getId() == 0) {
create(function);
} else {
update(function);
}
}
@Transactional
private void create(IdsFunction idsFunction) {
try {
em.persist(idsFunction);
}
catch (Exception e) {
System.out.println(e);
} finally {
em.close();
}
}
@Transactional
private void update(IdsFunction function) {
try {
em.merge(function);
} finally {
em.close();
}
}
}
and my starting JUnit test case is
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={"/applicationContext.xml"} )
public class IdsFunctionJpaControllerTest {
@Autowired
IdsFunctionJpaController dao;
@Test
@Transactional
public void addFunction() {
IdsFunction function = new IdsFunction();
function.setDescription("Test Function Description");
dao.save(function);
assertTrue(function.getId() != 0);
}
}
What I'm trying to do here is simply test that the entity has been created, but this test fails. If I remove the @Transactional
annotation, then the test passes, but the test entity remains in the database. What am I doing wrong?
Regards