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

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

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

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

难道我也在用这个注解?

@FixMethodOrder(MethodSorters.NAME_ASCENDING)

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

Annotating a public void method with @Before causes that method to be run before the Test method.

如果你想运行一个方法在所有测试前后只执行一次,你可以使用@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.

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