Daniel Daniel - 5 months ago 20
Java Question

Different teardown for each @Test in jUnit

Is there way to define a different teardown for each @Test in jUnit?

Answer

Use the @After annotation to indicate the method(s) to be run after every @Test.

The full suite of annotations like this are:

  • @BeforeClass - before all @Tests are run
  • @Before - before each @Test is run
  • @After - after each @Test is run
  • @AfterClass - after all @Tests are run

I just realised I may not have understood the question. If you are asking how to associate a particular teardown method to a particular @Test method, there is no need for annotations: Simply call it at the end of your test method in a finally:

@Test
public void someTest() {
    try {
        // test something
    } finally {
        someParticularTearDown();
    }
}
Comments