【问题标题】:Enabling assertions in Gradle/JUnit在 Gradle/JUnit 中启用断言
【发布时间】:2018-06-18 17:07:39
【问题描述】:

我的项目使用 gradle 和 JUnit 5.01。 JUnit 断言工作正常。但是,我在测试代码本身中的常规 Java 断言没有触发。我希望一个失败的断言会抛出一个被 JUnit 捕获和报告的 AssertionError。

我发现了这个:How to disable assert in gradle test,因此创建了这个 build.gradle:

buildscript {
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath 'org.junit.platform:junit-platform-gradle-plugin:1.0.2'
    }
}

apply plugin: 'java'
apply plugin: 'application'
apply plugin: 'maven'
apply plugin: 'org.junit.platform.gradle.plugin'

compileJava {
    options.compilerArgs += "-Xlint:unchecked"
}

tasks.withType(Test) {
    enableAssertions = true
}

repositories {
    mavenCentral()
}

dependencies {
    testCompile('org.junit.jupiter:junit-jupiter-api:5.0.1')
    testCompile('org.apiguardian:apiguardian-api:1.0.0')
    testRuntime('org.junit.jupiter:junit-jupiter-engine:5.0.1')
}

// Define the main class for the application
mainClassName = 'CMS'

jar {
    manifest {
        attributes 'Implementation-Title': 'CMS',
                   'Main-Class': 'com.brandli.cms.CMS'
    }
}

junitPlatform {
    filters {
        includeClassNamePattern '.*'
    }
}

test {
    testLogging {
        exceptionFormat = 'full'
    }
}

我做错了什么?

【问题讨论】:

  • 你能调试你的测试并确认抛出了断言错误吗?
  • 是的。我在必须击中它的地方放置了一个 assert false 。我在 JUnit 之外运行代码并在启用断言 (-ea) 的情况下运行它,它达到了我的断言。但是使用 JUnit(“构建”gradle 目标)运行它却没有。 (它后来在我的测试中遇到了一个 JUnit 断言。)所以我知道代码在没有启用 java 断言的情况下运行。

标签: java gradle junit build.gradle junit5


【解决方案1】:

深入研究 gradle,并进行大量实验,让我找到了替代

tasks.withType(Test) {
    enableAssertions = true
}

junitPlatformTest {
    enableAssertions = true
}

成功了。我不知道为什么。

【讨论】:

  • JUnit 5 是通过 JUnit 团队编写的插件支持的,而不是 gradle 的“原生”(目前)。考虑到这一点,您的发现并不令人惊讶。在实现原生支持之前会有一些问题。作为另一个 gradle 用户,我希望这会尽快发生
  • 对于 Kotlin DSL?
猜你喜欢
  • 2010-12-20
  • 1970-01-01
  • 2018-12-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-12-25
  • 1970-01-01
相关资源
最近更新 更多