簡體   English   中英

如何在多模塊項目中訪問gradle中的測試jar

[英]How to access tests jar in gradle in multi-module project

我有多模塊項目。 我需要從其中一個模塊引用其他模塊的測試類。 我試着這樣配置:

// core project
val testJar by tasks.registering(Jar::class) {
    archiveClassifier.set("tests")
    from(project.the<SourceSetContainer>()["test"].output)
}
val testArtifact by configurations.creating
artifacts.add(testArtifact.name, testJar)

我試圖從其他項目中引用該配置:

dependencies {
    // other dependencies ommited
    api(project(":core"))
    testImplementation(project(path = ":core", configuration = "testArtifact"))
}

但是這個配置不起作用。 其他項目的編譯失敗,因為它沒有從core項目中看到所需的測試類。 依賴洞察:

./gradlew :service:dependencyInsight --dependency core --configuration testCompileClasspath

它給出了以下內容:

project :core
  variant "apiElements" [
    org.gradle.usage = java-api
  ]
  variant "testArtifact" [
    Requested attributes not found in the selected variant:
      org.gradle.usage = java-api
  ]

我正在努力理解如何使配置工作以便我可以編譯service項目的測試類。 使用 Kotlin DSL 在 Gradle 5.2.1 上運行。

因此,上述內容適用於命令行,但不適用於 IDE。

這是一個基於變體感知依賴管理的變體:

plugins {
    `java-library`
}

repositories {
    mavenCentral()
}

group = "org.test"
version = "1.0"

val testJar by tasks.registering(Jar::class) {
    archiveClassifier.set("tests")
    from(project.the<SourceSetContainer>()["test"].output)
}

// Create a configuration for runtime
val testRuntimeElements by configurations.creating {
    isCanBeConsumed = true
    isCanBeResolved = false
    attributes {
        attribute(Usage.USAGE_ATTRIBUTE, project.objects.named(Usage::class, Usage.JAVA_RUNTIME_JARS))
    }
    outgoing {
        // Indicate a different capability (defaults to group:name:version)
        capability("org.test:lib-test:$version")
    }
}

// Second configuration declaration, this is because of the API vs runtime difference Gradle makes and rules around valid multiple variant selection
val testApiElements by configurations.creating {
    isCanBeConsumed = true
    isCanBeResolved = false
    attributes {
        // API instead of runtime usage
        attribute(Usage.USAGE_ATTRIBUTE, project.objects.named(Usage::class, Usage.JAVA_API_JARS))
    }
    outgoing {
        // Same capability
        capability("org.test:lib-test:$version")
    }
}

artifacts.add(testRuntimeElements.name, testJar)
artifacts.add(testApiElements.name, testJar)

由於變量感知依賴管理規則,上面看起來很多。 但是如果它是在插件中提取的,那么大部分都可以被分解出來。

而在消費者方面:

testImplementation(project(":lib")) {
    capabilities {
        // Indicate we want a variant with a specific capability
        requireCapability("org.test:lib-test")
    }
}

請注意,這需要 Gradle 5.3.1。 在 IntelliJ 2019.1 中導入項目正確連接依賴項,測試代碼可以在 IDE 中編譯。

哪個IDE? 它在終端和 IDE 中都適用於我:我使用 IntelliJ(2019.3)和 Gradle(6.0.1,而不是 Kotlin DSL)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM