27

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

Daniel
  • 417
  • 1
  • 7
  • 14

3 Answers3

53

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();
    }
}
hendalst
  • 2,957
  • 1
  • 24
  • 25
Bohemian
  • 412,405
  • 93
  • 575
  • 722
  • 1
    This is not exactly optimal since you will have to repeat this code for each test method. – Cedric Beust Jul 26 '11 at 21:31
  • That last example was only to cover a possible interpretation of the question - I personally would rarely do this, but it is nevertheless the simplest option I can think of for having different teardown methods for different @Tests. – Bohemian Jul 26 '11 at 22:27
  • 3
    There is a drawback with using try-finally for your teardown; if your normal junit setup takes a screenshot or logs the application state, this won't happen until the `finally` code has been run i.e. it won't capture the state of the application when the failure occurred. – Vince Bowdren Apr 24 '15 at 15:27
6

The point of grouping test methods together in the same class is so they can share things, that includes having the same setup and teardown. So, yes, you can define separate teardowns for each test, but you do so by putting the @Test methods in different classes.

Once you start having separate teardown methods the rationale for why you would want to group the tests together in the same class is not apparent. So you could manage this situation by being flexible about how you group your tests in classes.

Nathan Hughes
  • 94,330
  • 19
  • 181
  • 276
  • Yes, instead consider placing the set-up and tear-down code inside your `@Test` method. However, take care that the tear-down code is called even if an exception is thrown, by using `try`...`finally`. – Raedwald Jul 26 '11 at 13:12
  • 1
    @Raedwald: yes, Bohemian's approach is one way to do it, but you lose some of the power of the framework since now you have to add a finally block. – Nathan Hughes Jul 26 '11 at 13:13
1

There is no easy way to do this in JUnit. With TestNG, you can put your methods in groups, so you can define specific @BeforeMethod/@AfterMethod that only get run around certain groups.

Cedric Beust
  • 15,480
  • 2
  • 55
  • 55