varunkr
varunkr

Reputation: 5552

JUnit4: @Transactional removes data even before testcase is completed

In my Spring project I am running certain testcases using JUnit4. I use @Transactional to remove any changes made to the db during the testcases so that the new testcase gets the same initial db state. The problem is that in one of my testcases I insert some values in the db and later use them again in the same test. It looks like @Transactional removes the entries even before the test case is finished and as such my test doesn't run as expected. How can I resolve this issue?

It is something like this

@Test()
@Transactional
    // Add entries to db and do some asserts

    // Use those entries to do some more asserts
}

The second part doesn't work coz the entries are gone. Can someone please help. Thanks in advance !!

Upvotes: 0

Views: 61

Answers (1)

Jaiwo99
Jaiwo99

Reputation: 10017

You should only do this in test code, not in production code

This is generally not a good idea to manipulate transaction manually, but it should be fine for a test, you just need to do this:

@Test()
@Transactional
    // Add entries to db and do some asserts
    sessionFactory.getCurrentSession().flush()
    sessionFactory.getCurrentSession().clear()
    // Use those entries to do some more asserts
}

The method can be different.. but you can see the idea..

Upvotes: 1

Related Questions