user2623609
user2623609

Reputation: 87

Can't get test code to find source code using gradle

I'm using gradle. I only have one project, broken up into source files, then test files. My test code cannot see the source code. When the test code tries to compile, it just says that the source code packages are not present. What gives?

When running "gradle build", or "gradle test", I get the following:

What went wrong:
Execution failed for task ':compileTestJava'.
Compilation failed; see the compiler error output for details.

Sample compilation error (because there's hundreds of these)

/tst/ContactsTests.java:1: error: package HoaryGuts does not exist
import HoaryGuts.AlertsHandlers;
                ^

Gradle build.gradle file:

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'
}

Upvotes: 1

Views: 1917

Answers (1)

Oleg Sklyar
Oleg Sklyar

Reputation: 10082

Just like maven, gradle uses main for production sources. These are normally defined under src/main/java for Java and test includes them just like it includes compile dependencies alongside of testCompile.

There is a reason for having src followed by a named configuration, followed by language: in your setup you do not provide a location for test resources which are very common and you make it more cumbersome to include other JVM languages such as Kotlin or Scala into the project. Maybe you do not need those, but there are rarely no good reasons to strongly deviate from the industry standard.

In any case, you did not move your main to a different location, you introduced a new source set source in addition to main (actually preserving main where they originally were). If you just specified new srcDir for main instead of introducing source (as you did for test) you would not need to extend compileClasspath and your main sources would be found in test.

If you do really want to stick to source rather than using main at a new location, in test you should add source compileClasspath and output to the classpath for test:

compileClasspath += sourceSets.source.compileClasspath + source.output + [whatever else you want to add]

But well, it is a poor choice.

Upvotes: 4

Related Questions