How to run JUnit tests with Gradle?

build.gradle, gradle, java, junit4

Solution

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

EDIT: If you are using JUnit 5 instead, there are more steps to complete, you should follow this tutorial.

Problem

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?

Original source