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
JUnit @Before and @After executing before and after every test
提问by Kingamere
I am running JUnit tests that test a Spring Boot application. I have a @Before
method and an @After
one. Then I have a bunch of @Test
methods which are the actual tests.
我正在运行测试 Spring Boot 应用程序的 JUnit 测试。我有一个@Before
方法和@After
一个。然后我有一堆@Test
方法,它们是实际测试。
However, my @Before
and @After
methods 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 @Before
and @After
. Quoting the documentation of @Before
, for example:
这是正常的行为@Before
和@After
。引用 的文档@Before
,例如:
Annotating a public void method with
@Before
causes that method to be run before theTest
method.
注释公共无效方法
@Before
会导致该方法在该Test
方法之前运行。
If you want to run a method only once before and after all the tests, you can use @BeforeClass
and @AfterClass
. Quoting the documentation of @BeforeClass
for example:
如果您想在所有测试前后只运行一次方法,您可以使用@BeforeClass
and @AfterClass
。引用@BeforeClass
例如的文档:
Annotating a public static void no-arg method with
@BeforeClass
causes 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 @Before
and @After
are 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 static
and take no arguments.
这正是@Before
和@After
应该做的。如果你想在整个测试类之前运行一些设置代码,你应该使用@BeforeClass
. 以同样的方式,如果你想在整个测试类执行后拆除,你应该使用@AfterClass
. 请注意,应用这两个注释的方法应该是public static
并且不带参数。