我有多个 JUnit 测试类要运行,每个测试类中都有多个测试。我有一个基本测试类,它是所有测试类的父类。有没有办法在基测试类中编写在 @BeforeAll
之前和 @AfterAll
之后对所有测试类仅执行一次的方法?或者是否有任何可以实现的接口(interface)
或可以扩展的任何类来解决这个问题?
BaseJUnitTest.class
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.platform.runner.JUnitPlatform;
import org.junit.runner.RunWith;
@RunWith(JUnitPlatform.class)
public class BaseJUnitTest {
// method to execute before all JUnit test classes
@BeforeAll
public static void beforeAll() throws Exception {
}
@AfterAll
public static void afterAll() throws Exception {
}
@BeforeEach
public void beaforeEachTest() {
}
@AfterEach
public void afterEachTest() {
}
// method to execute after all JUnit test classes
}
SampleTest.class
public class SampleTest extends BaseJUnitTest {
@Test
public void test1() {
System.out.println("SampleTest test1");
}
}
注意:我正在使用 JUnit 5,尽管在这种情况下我希望 JUnit 4 或 5 并不重要
最佳答案
我认为您需要一个“测试套件”而不是基本测试类。该套件将包含您的测试用例。在此测试套件类上,使用 @Beforeclass 和 @Afterclass 来包含套件中所有测试之前或之后需要完成的工作。
关于java - JUnit - 在 @BeforeAll 之前执行的方法和在 @AfterAll 之后执行的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47746650/