JUnit中如何执行不同的@Before

How to execute different @Before in JUnit

目前,如果我编写 @Before 方法,它将针对 JUnit 中存在的每个测试执行。但是我想要以下内容。

我需要多个@Before 方法,并且只需要为每个测试执行。

Example:
 @Before
  setUpBeforeForTest1AndTest3()

 @Before
 setUpBeforeForTest2AndTest4()

对于test1和test2,应该执行setUpBeforeForTest1AndTest3(),对于其他测试,应该执行setUpBeforeForTest2AndTest4。

我怎样才能做到这一点?

你无法通过这种方式实现。

为此,进行 2 个不同的测试 classes,一个包含测试 1 和测试 3,另一个包含测试 2 和测试 4。

如果您的所有测试都需要通用方法 classes,要么将它们外化到助手中,要么制作一个超级 class(通常称为 'TestBase' 或类似名称)提供它们.

你可以使用 Junit

@Rule TestName

然后在你的

@Before, depending on the test method name, do something differently.