简体   繁体   English

自定义 Java 注释以忽略 CI 服务器上的集成测试

[英]Custom Java Annotation to ignore integration tests on CI server

I was thinking it would be handy to have a custom annotation for junit methods and classes that contain integration tests.我认为为包含集成测试的 junit 方法和类提供自定义注释会很方便。 This annotation would effectively act like the @Ignore junit annotation when the tests are being executed on our CI (Jenkins) server and the test would run as normal on local dev machines.当测试在我们的 CI (Jenkins) 服务器上执行并且测试将在本地开发机器上正常运行时,此注释将有效地起到 @Ignore junit 注释的作用。 To determine if the machine running the tests should allow integration test execution I would check System.getenv("WORKSPACE") to see if it exists/contains "jenkins".要确定运行测试的机器是否应该允许执行集成测试,我会检查 System.getenv("WORKSPACE") 以查看它是否存在/包含“jenkins”。

I haven't written annotations before and am not familiar with junit's implementation details.之前没写过注解,对junit的实现细节不熟悉。 Is what I'm describing possible?我描述的可能吗? If so, how would I go about this?如果是这样,我将如何 go 关于这个?

JUnit 5 JUnit 5

JUnit 5 has Environment Variable Conditions for this purpose. JUnit 5 具有用于此目的的环境变量条件 In your case, try add the following:在您的情况下,请尝试添加以下内容:


@Test
@EnabledIfEnvironmentVariable(named = "WORKSPACE", matches = "jenkins")
void onlyOnJenkins() {
    // ...
}

@Test
@DisabledIfEnvironmentVariable(named = "WORKSPACE", matches = "jenkins")
void notOnJenkins() {
    // ...
}

Note that the matches annotation attribute is a regex that supports wildcards.请注意, matches注释属性是一个支持通配符的正则表达式。 For details, please read the JavaDoc of @EnabledIfEnvironmentVariable and @DisabledIfEnvironmentVariable详情请阅读@EnabledIfEnvironmentVariable@DisabledIfEnvironmentVariable的JavaDoc

The Conditional Test Execution chapter in the JUnit user guide has more annotations and examples that you may find useful. JUnit 用户指南中的条件测试执行章节包含更多您可能会发现有用的注释和示例。


JUnit 4 JUnit 4

Please read this answer to learn how org.junit.Assume can be used to conditionally execute tests.请阅读此答案以了解如何使用org.junit.Assume有条件地执行测试。

Great information, thank you.很好的信息,谢谢。 I'm going to have to add a tech debt item in our backlog for upgrading to Junit 5.我将不得不在我们的待办事项中添加一个技术债务项目以升级到 Junit 5。

However, Assume did exactly what I needed.但是,假设正是我需要的。 I was able to add the following to my test class:我能够将以下内容添加到我的测试 class 中:

    @Before
    public void checkHost(){
        final String workspaceKey = "WORKSPACE";
        final String workspaceValue = System.getenv(workspaceKey);
        final boolean isJenkins = StringUtils.contains(workspaceValue, "Jenkins");
        log.info("checkHost(): " + workspaceKey + ":" + workspaceValue + " -> isJenkins: " + isJenkins);
        assumeFalse(isJenkins);
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM