Многопроектные интеграционные тесты Gradle с Junit5 - PullRequest
1 голос
/ 28 марта 2019

Как я могу создать интеграционные тесты с использованием Gradle 5.2 и JUnit 5.3 в многопроектном файле сборки?

Это мой текущий файл сборки:

buildscript {
  repositories {
    maven {
      url "https://plugins.gradle.org/m2/"
    }
  }
  dependencies {
    classpath "gradle.plugin.com.github.spotbugs:spotbugs-gradle-plugin:1.6.10"
    classpath 'org.owasp:dependency-check-gradle:5.0.0-M2'
  }
}


allprojects {
  defaultTasks 'clean', 'build', 'publish', 'installDist'
  group = 'coyote'
  version = '0.1.0'
}

subprojects {

  apply plugin: 'java'
  apply plugin: 'jacoco'
  apply plugin: "com.github.spotbugs"
  apply plugin: 'org.owasp.dependencycheck'
  apply plugin: 'maven-publish'
  apply plugin: 'application'
  apply plugin: 'eclipse'
  apply plugin: 'idea'

  repositories {
    jcenter()
    mavenCentral()
  }

  dependencies {
    testImplementation ("org.junit.jupiter:junit-jupiter-api:5.3.2")
    testRuntimeOnly ("org.junit.jupiter:junit-jupiter-engine:5.3.2")
    spotbugsPlugins ("com.h3xstream.findsecbugs:findsecbugs-plugin:1.8.0")
  }

  tasks.withType(Test) {
    useJUnitPlatform()
  }

  apply from: "$rootDir/integration-test.gradle"

  check.dependsOn jacocoTestCoverageVerification
  check.dependsOn dependencyCheckAnalyze

  spotbugs {
    effort = "max"
    reportLevel = "low"
    ignoreFailures = true
    showProgress = true
  }

  jacocoTestReport {
    reports {
      xml.enabled true
      html.enabled true
    }
  }

  check.dependsOn jacocoTestReport

  tasks.withType(com.github.spotbugs.SpotBugsTask) {
    reports {
      xml.enabled false
      html.enabled true
    }
  }

}

Файл integration-test.gradle, который я применяю в строке 46, содержит следующее:

sourceSets {
    itest {
        compileClasspath += sourceSets.main.output + configurations.testCompile
        runtimeClasspath += output + compileClasspath + configurations.testRuntime
    }
}

idea {
    module {
        testSourceDirs += sourceSets.itest.java.srcDirs
        testResourceDirs += sourceSets.itest.resources.srcDirs
        scopes.TEST.plus += [configurations.itestCompile]
    }
}

task itest(type: Test) {
    description = 'Runs the integration tests.'
    group = 'verification'
    testClassesDirs = sourceSets.itest.output.classesDirs
    classpath = sourceSets.itest.runtimeClasspath
    outputs.upToDateWhen { false }
}

В Intellij все работает хорошо, но JUnit5 не добавляется в путь к классам, поэтому никакие тесты в каталогах itest не могут найти библиотеки JUnit.

Выполнение gradlew itest завершается ошибкой с аналогичными результатами, когда классы JUnit не найдены.

Я пытался добавить использование useJUnitPlatform() непосредственно в задачу itest, но безуспешно. Я также попытался поместить все в файл build.gradle безуспешно.

В конце концов, я бы хотел использовать один и тот же шаблон для определения нагрузочного тестирования и тестирования безопасности, запуская их отдельно как часть конвейера CI / CD, поэтому размещение всего аккуратно в их собственных каталогах в соответствующих проектах предпочтительнее, чем смешивать все в один тестовый каталог и использование тегов.

Это также помогает другим командам моделировать практики CI / CD, поэтому предпочтительнее использовать Gradle 5 и JUnit 5, как было задумано, а не обходные пути или хаки, чтобы заставить вещи работать. Приемлемо узнать, что эти версии не работают вместе или что в настоящее время есть дефекты / проблемы, препятствующие такому подходу. Надеюсь, это не проблема, и я просто упускаю что-то простое.

1 Ответ

1 голос
/ 01 апреля 2019

Решение заключается в том, что мне нужно было включить зависимости JUnit 5 самостоятельно. Ниже приведен правильный integration-test.gradle файл:

sourceSets {
    itest {
        compileClasspath += sourceSets.main.output + configurations.testCompile
        runtimeClasspath += output + compileClasspath + configurations.testRuntime
    }
}

idea {
    module {
        testSourceDirs += sourceSets.itest.java.srcDirs
        testResourceDirs += sourceSets.itest.resources.srcDirs
        scopes.TEST.plus += [configurations.itestCompile]
    }
}

dependencies {
    itestImplementation ("org.junit.jupiter:junit-jupiter-api:5.3.2")
    itestRuntimeOnly ("org.junit.jupiter:junit-jupiter-engine:5.3.2")
}

task itest(type: Test) {
    description = 'Runs the integration tests.'
    group = 'verification'
    testClassesDirs = sourceSets.itest.output.classesDirs
    classpath = sourceSets.itest.runtimeClasspath
    outputs.upToDateWhen { false }
}
...