Q Liu Q Liu - 2 months ago 47
Java Question

How to run JUnit tests with Gradle?

Currently I have the following build.gradle file:

apply plugin: 'java'

sourceSets {
main {
java {
srcDir 'src/model'
}
}
}

dependencies {
compile files('libs/mnist-tools.jar', 'libs/gson-2.2.4.jar')
runtime fileTree(dir: 'libs', include: '*.jar')
}




This build.gradle file is for my repository here. All of my main files are in src/model/ and their respective tests are in test/model.

How do I add a JUnit 4 dependency correctly and then run those tests in the folders of tests/model?

Answer Source

How do I add a junit 4 dependency correctly?

Assuming you're resolving against a standard Maven (or equivalent) repo:

dependencies {
    ...
    testCompile "junit:junit:4.11"  // Or whatever version
}

Run those tests in the folders of tests/model?

You define your test source set the same way:

sourceSets {
    ...

    test {
        java {
            srcDirs = ["test/model"]  // Note @Peter's comment below
        }
    }
}

Then invoke the tests as:

./gradlew test