How to run JUnit tests with Gradle? How to run JUnit tests with Gradle? java java

How to run JUnit tests with Gradle?


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.


If you set up your project with the default gradle package structure, i.e.:

src/main/javasrc/main/resourcessrc/test/javasrc/test/resources

then you won't need to modify sourceSets to run your tests. Gradle will figure out that your test classes and resources are in src/test. You can then run as Oliver says above. One thing to note: Be careful when setting property files and running your test classes with both gradle and you IDE. I use Eclipse, and when running JUnit from it, Eclipse chooses one classpath (the bin directory) whereas gradle chooses another (the build directory). This can lead to confusion if you edit a resource file, and don't see your change reflected at test runtime.


If you created your project with Spring Initializr, everything should be configured correctly and all you need to do is run...

./gradlew clean test --info
  • Use --info if you want to see test output.
  • Use clean if you want to re-run tests that have already passed since the last change.

Dependencies required in build.gradle for testing in Spring Boot...

dependencies {    compile('org.springframework.boot:spring-boot-starter')    testCompile('org.springframework.boot:spring-boot-starter-test')}

For some reason the test runner doesn't tell you this, but it produces an HTML report in build/reports/tests/test/index.html.