简体   繁体   中英

Clean up database after JUnit test.

I have a unit test that inserts rows into the database, and I'd like DBUnit to automatically clean up those rows afterwards (DBUnit does not initially insert those rows - that's purely the responsibility of the code being tested).

Thanks.

使您的INSERT / UPDATE / DELETE查询具有事务性,并在测试完成后回滚它们。

If you use JUnit4, then you can declare a function with @AfterClass annotation: it will execute after all tests and you can remove all the rows you added in your tables.

In JUnit3, you don't have any equivalent, but you can override the tearDown() method, which will be executed after each test (equivalent of @After annotation in JUnit4).

If you allocate external resources(file/DB) in a Before method you need to release them after the test runs. Annotating a public void method with @After causes that method to be run after the Test method. All @After methods are guaranteed to run even if a Before or Test method throws an exception. The @After methods declared in superclasses will be run after those of the current class.

Example shows file as resource but you can use it for your DB cleanup.

 public class Example {
    File output;
    @Before public void createOutputFile() {
          output= new File(...);
    }
    @Test public void something() {
          ...
    }
    @After public void deleteOutputFile() {
          output.delete();
    }
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM