Different teardown for each @Test in jUnit

2019-03-24 05:14发布

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

3条回答
欢心
2楼-- · 2019-03-24 05:50

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.

查看更多
SAY GOODBYE
3楼-- · 2019-03-24 06:06

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();
    }
}
查看更多
Summer. ? 凉城
4楼-- · 2019-03-24 06:13

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.

查看更多
登录 后发表回答