How to run JUnit tests with Gradle?

Viewed 219083

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?

6 Answers

This is for Kotlin DSL (build.gradle.kts) and using JUnit 5 (JUnit platform):

tasks.test {
    // Discover and execute JUnit4-based tests
    useJUnit()

    // Discover and execute TestNG-based tests
    useTestNG()

    // Discover and execute JUnit Platform-based (JUnit 5, JUnit Jupiter) tests
    // Note that JUnit 5 has the ability to execute JUnit 4 tests as well
    useJUnitPlatform()
}

dependencies {
    testImplementation("org.junit.jupiter:junit-jupiter:5.8.2")
    // ...
}

testCompile is deprecated. Gradle 7 compatible:

dependencies {
...
   testImplementation 'junit:junit:4.13'
}

and if you use the default folder structure (src/test/java/...) the test section is simply:

test {
    useJUnit()
}

Finally:

gradlew clean test

Alos see: https://docs.gradle.org/current/userguide/java_testing.html

If you want to add a sourceSet for testing in addition to all the existing ones, within a module regardless of the active flavor:

sourceSets {
    test {
        java.srcDirs += [
                'src/customDir/test/kotlin'
        ]
        print(java.srcDirs)   // Clean
    }
}

Pay attention to the operator += and if you want to run integration tests change test to androidTest.

GL

Related