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("mail@gmail.com");
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);
}