Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to rollback a database transaction when testing services with Spring in JUnit?
    primarykey
    data
    text
    <p>I have no problem testing my DAO and services, but when I test <code>INSERT</code>s or <code>UPDATE</code>s I want to rollback the transaction and not effect my database.</p> <p>I'm using <code>@Transactional</code> inside my services to manage transactions. I want to know, is it possible to know if a transaction will be fine, but rollback it to prevent altering database?</p> <p>This is my Test:</p> <pre><code>@RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = "classpath:/META-INF/spring.cfg.xml") @TransactionConfiguration(defaultRollback=true) public class MyServiceTest extends AbstractJUnit38SpringContextTests { @Autowired private MyService myService; @BeforeClass public static void setUpClass() throws Exception { } @AfterClass public static void tearDownClass() throws Exception { } @Test public void testInsert(){ long id = myService.addPerson( "JUNIT" ); assertNotNull( id ); if( id &lt; 1 ){ fail(); } } } </code></pre> <p>The problem is that this test will fail because transaction was rollbacked, but the insert is OK! If I remove <code>@TransactionConfiguration(defaultRollback=true)</code> then the test pass but a new record will be inserted into database.</p> <pre><code>@Test @Transactional @Rollback(true) public void testInsert(){ long id = myService.addPerson( "JUNIT" ); assertNotNull(id); if( id &lt; 1 ){ fail(); } } </code></pre> <p>Now can test pass correctly, but rollback is ignored and the record is inserted into the database. I have annotated the method <code>addPerson()</code> inside myService with <code>@Transactional</code>, obviously. Why is the rollback being ignored?</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload