3
votes

Gradle with apply plugin: 'java' in build.gradle. The file will create a .jar file and the test task is running junit tests:

apply plugin: 'java'

repositories {
    mavenCentral()
}

dependencies {
  testCompile 'junit:junit:4.12'
}

This is working. But to make sure the public API tests are working with the generated .jar file I want that the 'test' task is running the test with the generated .jar file from the build/libs folder in classpath and not with the generate .class files from folder build/classes in in classpath.

Not working because the sourceSets is set global:

tasks.withType(Test) {
    sourceSets {
        main {
            java {
                exclude '**'
            }
        }
    }
}

Partly working: multiproject (test and jar separated in two gradle projects):

dependencies {
  compile project(":jar_project")
  testCompile 'junit:junit:4.12'
}

in this case jar_project.jar is used but package private test are also executed without an error.

Do somebody have an idea how to run the tests with the .jar as dependency and ignoring the .class files?

Thank you, pulp

1
see solution in this post: discuss.gradle.org/t/… - M.Ricciuti
Thank you for the link. I tried: dependencies { testCompile files("junit/junit-4.12.jar") } test { classpath = project.files("build/classes/java/test", "junit/junit-4.12.jar", "${jar.archivePath}" ) But non public classes are still tested without an error. The resulting command line ‘java.exe …..’ in Process Explorer task manager does not contain the jar file in classpath so it’s difficult to find out what’s going on. Maybe Gradle using reflection to access the classes and methods. - pulp
What do you mean by “package private test are also executed without an error” and “non public classes are still tested without an error”? Have you customized the jar task to exclude such classes from the jar file? - Chriki
@Chriki: My thought was wrong. Since the unit test code is in a package with the same name as the package from the package private functions its correct that no error is generated. - pulp

1 Answers

0
votes

The problem is that the test task does not depend on the jar task, which sort of makes sense because the jar is supposed to package the classes, so there should be no reason for tests to depend on that jar.

You can force the dependency by:

test {
  dependsOn jar
  doFirst {
    classpath += jar.outputs.files
  }
}

Now the jar will be on the test classpath