java JUnit @Before 和 @After 在每次测试之前和之后执行

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32935611/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 20:58:43  来源:igfitidea点击:

JUnit @Before and @After executing before and after every test

javaunit-testingjunitspring-bootjunit4

提问by Kingamere

I am running JUnit tests that test a Spring Boot application. I have a @Beforemethod and an @Afterone. Then I have a bunch of @Testmethods which are the actual tests.

我正在运行测试 Spring Boot 应用程序的 JUnit 测试。我有一个@Before方法和@After一个。然后我有一堆@Test方法,它们是实际测试。

However, my @Beforeand @Aftermethods execute before and after each test, respectively, instead of executing once before all the tests, and once after all the tests.

但是,my@Before@After方法分别在每次测试之前和之后执行,而不是在所有测试之前和所有测试之后执行一次。

Could it be that I'm also using this annotation?

难道我也在使用这个注释?

@FixMethodOrder(MethodSorters.NAME_ASCENDING)

回答by Tunaki

This is the normal behaviour of @Beforeand @After. Quoting the documentation of @Before, for example:

这是正常的行为@Before@After。引用 的文档@Before,例如:

Annotating a public void method with @Beforecauses that method to be run before the Testmethod.

注释公共无效方法@Before会导致该方法在该Test方法之前运行。

If you want to run a method only once before and after all the tests, you can use @BeforeClassand @AfterClass. Quoting the documentation of @BeforeClassfor example:

如果您想在所有测试前后只运行一次方法,您可以使用@BeforeClassand @AfterClass。引用@BeforeClass例如的文档:

Annotating a public static void no-arg method with @BeforeClasscauses it to be run once before any of the test methods in the class.

注释 public static void no-arg 方法@BeforeClass使其在类中的任何测试方法之前运行一次。

回答by Mureinik

That is exactly what @Beforeand @Afterare supposed to do. If you want to run some setup code before an entire test class, you should use @BeforeClass. In the same fashion, if you want to tear down after an entire test class has been executed, you should use @AfterClass. Note that the methods these two annotations are applied to should be public staticand take no arguments.

这正是@Before@After应该做的。如果你想在整个测试类之前运行一些设置代码,你应该使用@BeforeClass. 以同样的方式,如果你想在整个测试类执行后拆除,你应该使用@AfterClass. 请注意,应用这两个注释的方法应该是public static并且不带参数。