Highly Opinionated Thoughts on Programming

by Elnur Abdurrakhimov


Separating Different Types of Tests in Gradle

May 11, 2014


Let’s say you have a Gradle application with a standard layout:

src
├── main
│   └── java    
└── test
    └── java
build.gradle

The real code goes to src/main/java and unit tests go to src/test/java.

Now let’s say it’s a REST API application and you want to add API tests. You could put them into src/test/java right next to unit tests, but that makes it hard to run different types of tests separately.

A solution idiomatic to Gradle is to create a separate source set, configuration, and task for each type of tests. Here’s what you add to your build.gradle file:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
sourceSets {  
    apiTest {
        compileClasspath += main.output + test.output
        runtimeClasspath += main.output + test.output
    }
}

configurations {  
    apiTestCompile.extendsFrom testCompile
    apiTestRuntime.extendsFrom testRuntime
}

task apiTest(type: Test) {  
    testClassesDir = sourceSets.apiTest.output.classesDir
    classpath = sourceSets.apiTest.runtimeClasspath
}

Put your API tests into src/apiTest/java:

src
├── apiTest
│   └── java
├── main
│   └── java    
└── test
    └── java
build.gradle

Now you can run your API tests separately:

./gradlew apiTest

The same approach can be applied to add as many types of tests as you need: integration, UI, etc.

Enjoy.



© Elnur Abdurrakhimov