I have the following test where I need to show that my transaction works and can do rollback. The problem here is my RuntimeException is executed before the data is entered into the database. So rollback doesn't happen. How do I set up this test?
@Test @Rollback(true) public void testForTransactionRollback() throws ClassNotFoundException, SQLException { User user = new User(); user.setFirstName("Ivan"); user.setLastName("Ivanov"); user.setPhoneNumber("18000000"); user.setEmail("[email protected]"); user.setCardNumber("4111111111111111"); user.setDeliveryAddress("address"); user.setComment("comment"); String result = ""; final ClientDAO clientDao1 = Mockito.spy(new ClientDAOImpl()); final ClientDAOImpl clientDaoImpl = (ClientDAOImpl) clientDao1; Mockito.when(clientDao1.insert(user)).thenThrow(new RuntimeException()); try { clientDao1.insert(user); } catch (final RuntimeException e) { System.out.println("Expected failure to trigger transaction caught"); } finally { user = clientDao1.get(1L); if (user != null) { result = user.getFirstName(); } } Assert.assertEquals("it should be equal", "", result); }
Rollback(true)? I'm assuming you want to test an actual method in your production code, otherwise this test will actually prove nothing other than your test being able to perform a rollback. You should call your method responsible for handling the transaction, ensure that it fails and then assert that nothing was updated in the database.