/** Ensures that transactions are rolled back when a runtime exception occurs. */ public void testTransactionRolledBackOnRuntimeException() { /* * Create mock entity manager factory which returns a mock * entity manager when asked. */ EntityManagerFactory emf = mock(EntityManagerFactory.class); EntityManager em = mock(EntityManager.class); when(emf.create()).thenReturn(em); EntityTransaction tx = mock(EntityTransaction.class); when(em.getTransaction()).thenReturn(tx); Injector injector = Guice.createInjector(new TestModule(emf, true)); OuterTransactedClass outer = injector.getInstance(OuterTransactedClass.class); try { outer.doSomethingInATransaction(); fail("A runtime exception should have been thrown"); } catch (RuntimeException ignored) { } // emf.create should only have been called once. verify(emf).create(); verify(tx).begin(); verify(tx).rollback(); verify(em).close(); }
public void testStartTransaction() { /* * Create mock entity manager factory which returns a mock * entity manager when asked. */ EntityManagerFactory emf = mock(EntityManagerFactory.class); EntityManager em = mock(EntityManager.class); when(emf.create()).thenReturn(em); EntityTransaction tx = mock(EntityTransaction.class); when(em.getTransaction()).thenReturn(tx); Injector injector = Guice.createInjector(new TestModule(emf, false)); OuterTransactedClass outer = injector.getInstance(OuterTransactedClass.class); outer.doSomethingInATransaction(); // emf.create should only have been called once. verify(emf).create(); verify(tx).begin(); verify(tx).commit(); verify(em).close(); }