Spring Junit DAO Test Transaction Rollback Issue

Reading Time: < 1 minute

For a long while i have been having this crazy incident in Spring transaction which cause me headaches while conducting tests for backend development. The Issue i face is that I’ve dozen of test methods which test different functionality of my Database methods, firstly creation methods are being conducted and I do carry out other editing deletion test, but I need data for it.

So after the data is created next steps failed because in spring test transaction is whether successfully ended up or not it is rolled back, so after I’ve checked it ended up with the real solution. First of all you can directly set it off with the “TransactionConfiguration” annotation and in each method you define you can set the rollback as I share the code below, the rest depends on your choice

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
@Transactional
@TransactionConfiguration(defaultRollback = false)
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class AppDAOTest {

    @Autowired
    private AppService appService;

    private final static String parentCatName = "TESTPARENTCATEGORY";
    private final static String childCatName = "TESTCHILDCATEGORY";
    private final static String grandChildCatName = "TESTGRANDCHILDCATEGORY";
    private final static String postName = "TESTPOST";
    private final static String userName = "TESTUSER";
    private final static String userName2 = "TESTUSERTEST";
    private Date date = new Date();

    private static long prantCatId;
    private static long childCatId;
    private static long grandChildCatId;

    @Before
    public void setUp() throws Exception {

    }

    @After
    public void tearDown() throws Exception {
        //Delete the parent category
        //appService.deleteCategory(appService.getCategoryByName(parentCatName));
    }

    @Test
    @Rollback(false)
    public void stage01_CreateParentCategoryTest() {
        //Create the parent category
        appService.createCategory(new Category(parentCatName, date, null, null, null));

        //Fetch the parent category
        Category category = appService.getCategoryByName(parentCatName);

        //Check whether the object is not null
        assertNotNull(category);

        //Check the parent category name does match
        assertEquals(parentCatName, category.getCategoryName());
    }
}