1

For my JUnit 4 tests, a handful of database inserts have to be performed by code. However, the application framework has some overhead, which makes this step really slow.

To save time, I tried to run this initial step only one time before the first test execution. The tests perform read operations only, no writes, so the risk of test side effects is minimal.

Using @Transactional however, all inserted data is reverted after the first test, causing test failures or false positives for all other tests.

    @RunWith(SpringJUnit4ClassRunner.class)
    @ContextConfiguration(locations = { ... })
    @Transactional
    public class DatabaseFilterTest {
    
    static boolean setUpIsDone = false;

    @Before
    public void setUp() {
      ...
      if (!setUpIsDone) {
          // do the setup
          prepareData();
          setUpIsDone = true;
      }
    }

With JUnit 4, is there a way to perform the transaction rollback at the end, after all tests have been run?

1
  • consider using testcontainer with prepared database as container Commented Sep 28 at 18:28

1 Answer 1

0

Mark your setup method or helper as not transactional, so it persists data once and survives across test methods:

Here the trick is: don’t put @Transactional on the class. Instead, only annotate test methods that need rollback.

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { ... })
public class DatabaseFilterTest {

    private static boolean setUpIsDone = false;

    @Autowired
    private YourRepository repo;

    @Before
    public void setUp() {
        if (!setUpIsDone) {
            insertTestData(); // persists real data, not rolled back
            setUpIsDone = true;
        }
    }

    @Transactional  // applied only at method level if needed
    @Test
    public void testSomething() {
        ...
    }

    @Rollback(false) // ensures data is committed
    @Test
    public void insertTestData() {
        repo.save(...);
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.