4

I have some junit tests where I want to pre-populate the DB with some data that actually makes sense for the test:

@RunWith(SpringRunner.class)
@SpringBootTest
@ActiveProfiles("test")
public class MyTest {


@Sql("test_insert.sql") 
@Test
public void testInsert(){
  ...performs some inserts...
}
@Sql("test_delete.sql") //makes inserts to the db so to delete them
@Test
public void testDelete(){
    ...
}

I noticed that junit executes the tests by reverse order, meaning that my testDelete will be executed first.

Test insert seems to fail for a "duplicate row constraint" and that happens because the test_delete.sql scripts actually adds that row.

Would it to be possible to rollback the operations made by the @Sql and the test itself so that one test does not influence the others?

Phate
  • 6,066
  • 15
  • 73
  • 138
  • The answer by @lealceldeiro is correct: you just need to make the tests `@Transactional`. I recommend you read the _Testing_ chapter of the Spring Reference Manual. This is all documented. – Sam Brannen May 20 '18 at 11:09

1 Answers1

5

You just need to add @Transactional on top of the JUnit test class. This will revert all changes made to the database after every test has ran.

@RunWith(SpringRunner.class)
@SpringBootTest
@ActiveProfiles("test")
@Transactional           //  <-- @Transactional added
public class MyTest {


@Sql("test_insert.sql") 
@Test
public void testInsert(){
  ...performs some inserts...
}
@Sql("test_delete.sql") //makes inserts to the db so to delete them
@Test
public void testDelete(){
    ...
}
lealceldeiro
  • 14,342
  • 6
  • 49
  • 80
  • If like me you land here and despite the `@Transactional` your `@Sql` scripts are not rolled back, one possibility is that you have played around with `@TestExecutionListeners`, if so, make sure the `TransactionalTestExecutionListener.class` is present. – Ghurdyl Dec 12 '19 at 11:01