Search code examples
javaeclipsegradlejava-resources

Gradle does not copy package-local test resources


I'd like gradle to behave like Eclipse when it executes the tests. Here is a minimal setup:

plugins {
    id 'eclipse'
    id 'java'
}
repositories {
    mavenCentral()
}
dependencies {
    testImplementation 'org.junit.jupiter:junit-jupiter:5.8.1'
}
tasks.named('test') {
    useJUnitPlatform()
}

The source tree is:

└───src
    └───test
        └───java
            └───abc
                    package-local.txt
                    ResourceTest.java

And the actual test looks like this:

package abc;

import static org.junit.jupiter.api.Assertions.assertNotNull;
import org.junit.jupiter.api.Test;

public class ResourceTest {

    @Test
    void loadResource() {
        assertNotNull(getClass().getResource("package-local.txt"));
    }
    
}

This works when run from Eclipse, but fails with gradlew test because gradle will not copy src/test/java/abc/package-local.txt into the classpath that is used for test execution. Why is that and what do I need to do to get the same behavior as in Eclipse?


Solution

  • I found this can be achieved by redefining sourceSets. Eclipse will copy the entire directory tree including any non-java source files from both src/test/java as well as src/test/resources into the classpath used for the tests. To have gradle do the same, add this to build.gradle:

    sourceSets {
        test {
            resources.srcDirs = ['src/test/java','src/test/resources']
            resources.excludes = ['**/*.java']
        }
    }