JUnit: Setting Transaction boundry for Test Class
Solution 1
Use @Before to launch method before any test and @After to launch method after every test. Use @Transactional spring's annotation over a method or over a class to start transaction and @Rollback to rollback everything done in transaction.
@Before
public void setUp(){
//set up, before every test method
}
@Transactional
@Test
public void test(){
}
@Rollback
@After
public void tearDown(){
//tear down after every test method
}
Also there is same issue solved in another way.
Solution 2
In Spring just add @Transactional
annotation over your test case class:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"/testApplicationContext.xml"})
@Transactional //CRUCIAL!
public class MyTests{
Check out official documentation for very in-depth details, including @TransactionConfiguration
, @BeforeTransaction
, @AfterTransaction
and other features.
Solution 3
Use the annotation @Before
for methods that have to run before every testmethod and @After
to run after every testmethod.
You can take this article as a reference.
Ashika Umanga Umagiliya
Updated on June 13, 2022Comments
-
Ashika Umanga Umagiliya almost 2 years
I want to start the database transactions before start of any test method and rollback all transactions at the end of running all tests.
How to do thing?What annotations should I use ?
@RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = {"/testApplicationContext.xml"}) public class MyTests{ public void setUp(){ //Insert temporary data to Database } @Test public void testOne(){ //Do some DB transactions } @Test void testTwo(){ //Do some more DB transactions } public void tearDown(){ //Need to rollback all transactions } }
-
G. Demecki over 9 yearsYes, it is the simplest approach, but generally managing transactions in tests using
@Transactional
is strongly discouraged. You even wrote article on that topic: Spring Pitfalls: Transactional tests considered harmful :) -
Erica Kane almost 7 yearsI normally use the method given above but @G.Demecki is correct, I've been bitten a few times that way.