Database Cleanup after every junit test cases with

2019-04-13 05:09发布

问题:

I am using junit4 with spring to test my rest web services. For this, I am using HSQL in memory database.

To clean the records after every test case, I am removing all the records from tables.

But I want to delete only inserted records. I am adding data to database in two places:

  1. In Junit test cases.

  2. In the rest services.

I am making http calls to test the services. Also, I am using same in-memory database in rest services.

Kindly help me in removing only inserted records after each test cases.

Edited: My concern is deleting the inserted records in http calls to rest services. It is really hard to keep track of those records. They are part of my actual code.

回答1:

you could use @Before and @After methods to perform this activity.

Note that @Before will be executed before every test and @After will be executed after every Test .So @Before you should insert the records , now you know which records have been inserted , delete only them in @After

If you want to add few different records for each test then use try .... finally

like below

class Test{
     @Before
        public void setUp(){
             // insert x Records 
        }


      @After
        public void tearDown(){
             // delete x Records 
        }


         @Test
                public void someTest() throws Exception {
              //  ... insert few records 
                try{
                doSomething();
              }finally{
            //  deleteRecordsInserted for this test.
             }

            }

}