Different teardown for each @Test in jUnit

落爺英雄遲暮 提交于 2019-12-04 17:02:09

问题


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


回答1:


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



回答2:


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.




回答3:


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.



来源:https://stackoverflow.com/questions/6830342/different-teardown-for-each-test-in-junit

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!