Junit5- jupiter所有测试套件@BeforeAll @AfterAll不起作用

时间:2019-04-19 08:59:19

标签: spring-boot junit integration-testing spring-boot-test junit-jupiter

JUnitPlatform中的before和after方法不起作用。

代码在下面。

import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.platform.runner.JUnitPlatform;
import org.junit.platform.suite.api.SelectClasses;
import org.junit.runner.RunWith;

@RunWith(JUnitPlatform.class)
@SelectClasses({
        MyControllerTest.class
})
public class AdminAppTest {

    @BeforeAll
    public static void setUp() {
        System.out.println("setting up");
    }

    @AfterAll
    public static void tearDown() {
        System.out.println("tearing down");
    }
}

我只想在方法之前和之后运行。

谢谢

2 个答案:

答案 0 :(得分:1)

我可以引用JUnit 5 migration tipps

@Before@After不再存在;改为使用@BeforeEach@AfterEach

@BeforeClass@AfterClass不再存在;改为使用@BeforeAll@AfterAll

但是这些注释应在测试类中使用。套件类中的方法不会以这种方式调用。而且您应该知道套件和JUnit 5仍在进行中的事实(请参见Issue 744)。

答案 1 :(得分:0)

您可能要检查 classpath 中是否存在 org.junit.jupiter:junit-jupiter-engine

但是,最新版本的构建工具(带有surefire插件的Maven,Gradle,Eclipse,IntelliJ等)支持 junit-platform 。因此,您不需要将JUnit4与向后兼容的运行器一起使用。

通常情况下,您会处于以下情况:

  • 创建新项目,在这种情况下,您可以直接开始仅使用JUnit-Jupiter(并且在类路径中没有JUnit4)

  • 将项目从JUnit4迁移到JUnit5。在这里,您将需要两个引擎:JUnit-Vintage和JUnit-Jupiter,JUnit-Vintage涵盖了使用JUnit4 API的现有测试的兼容性,JUnit-Jupiter提供了更大的灵活性,包括扩展的组成(同时具有Spring,Mockito和参数化测试功能)时间)

当您受到无法更改的环境(构建工具和/或IDE)的约束时,使用JUnit4运行程序运行JUnit-Jupiter测试确实是一个极端的情况。

有关更多详细信息,JUnit团队可提供示例项目:

希望这会有所帮助!

相关问题