我正在使用 gradle。我只有一个项目,分为源文件,然后是测试文件。我的测试代码看不到源代码。当测试代码尝试编译时,它只是说源代码包不存在。给出了什么?
运行“gradle build”或“gradle test”时,我得到以下信息:
What went wrong:
Execution failed for task ':compileTestJava'.
Compilation failed; see the compiler error output for details.
示例编译错误(因为有数百个)
/tst/ContactsTests.java:1: error: package HoaryGuts does not exist
import HoaryGuts.AlertsHandlers;
^
Gradle build.gradle 文件:
apply plugin: 'java'
sourceCompatibility = 1.8
targetCompatibility = 1.8
version = '1.0'
repositories {
mavenCentral()
}
task getHomeDir << {
println gradle.gradleHomeDir
}
sourceSets {
source {
java {
srcDir "src"
}
resources {
srcDir "resources"
}
}
test {
java {
srcDir "tst"
}
compileClasspath = compileClasspath + configurations.compileOnly
}
}
test {
println "In the test function"
useTestNG()
testLogging {
exceptionFormat = 'full'
}
afterTest { desc, result ->
println "${desc.className} ${desc.name} ${result.resultType}"
}
outputs.upToDateWhen {false}
}
dependencies {
compile group: 'org.testng', name: 'testng', version: '6.9.10'
}
最佳答案
就像 Maven 一样,gradle 使用 main
作为生产源。这些通常在 Java 的 src/main/java
下定义,test
包含它们,就像它包含 compile
依赖项以及 testCompile
.
让 src
后跟命名配置和语言是有原因的:在您的设置中,您没有提供非常常见的测试资源的位置,这使得测试资源变得更加麻烦将其他 JVM 语言(例如 Kotlin 或 Scala)包含到项目中。也许您不需要这些,但很少有充分的理由强烈偏离行业标准。
无论如何,您都没有将 main
移动到其他位置,除了 main
之外,您还引入了一个新的源集 source
(实际上保留了 main 原来所在的位置)。如果您只是为 main
指定了新的 srcDir
而不是引入 source
(就像您在测试中所做的那样),则不需要扩展 compileClasspath
并且您的主要来源将在测试中找到。
如果您确实想坚持使用 source
而不是在新位置使用 main
,则应在 test
中添加 source
compileClasspath
和 output
到类路径进行测试:
compileClasspath += sourceSets.source.compileClasspath + source.output + [whatever else you want to add]
但是,这是一个糟糕的选择。
关于java - 无法获取测试代码使用gradle查找源代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50278171/