我有多模块项目。从一个模块中,我需要从其他模块中引用测试类。我试图这样配置:
// 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上运行。
答案 0 :(得分: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中进行编译。
答案 1 :(得分:0)
哪个IDE? 它在终端和IDE中都对我有效:我使用IntelliJ(2019.3)和Gradle(6.0.1,不是Kotlin DSL)