Uday Reddy
Uday Reddy

Reputation: 1471

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.

Upvotes: 0

Views: 4783

Answers (3)

eternay
eternay

Reputation: 3814

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).

Upvotes: 1

Juned Ahsan
Juned Ahsan

Reputation: 68715

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();
    }
 }

Upvotes: 1

duffymo
duffymo

Reputation: 308743

Make your INSERT/UPDATE/DELETE queries transactional and roll them back when the test is done.

Upvotes: 1

Related Questions