It’s recommended to separate integration tests from unit tests for several reasons. One is to shorten the feedback loop as the unit tests run way faster. In the case of a Java project using Gradle, it’s very common to split the project into multiple sub-projects, such as, common
, model
, application
…
Given this configuration, it could be difficult to have a helper class used by the unit and integration tests in the various sub-projects. As this is a test helper, we are not interested on having it next to the production code and we don’t want to copy the class to several sub-projects.
In order to solve this problem we may use the Gradle plugin for Test Fixtures.
The file build.gradle
could be very complex, but it’s true that a lot of features may be configured adding just one line. This is what happens here, we only need the following line:
apply plugin: 'java-test-fixtures'
Adding this line makes the directory /scr/testFixtures
available in our project. In this directory we can add the classes that we want to use in our tests.
Suppose we have a project comprised of “application” and “model”. In the “model” project we will store our domain objects and in the “application” project we will put the rest of the code.
If we want to generate our “test fixtures” in the “model” and consume them from the “application” project, the configuration should be similar to the following:
project(':application') {
dependencies {
implementation(project(':model'))
testImplementation(testFixtures(project(':model')))
}
}
project(':model') {
apply plugin: 'java-test-fixtures'
}
On the example below, the “application” project has access to the defined classes on the “model” project, it has access to both files on the directory /src/main/
and test fixtures on /srx/testFixtures
.
The “model” project would not have access to the defined classes on the “application” project.
Now let’s say that for our fixtures we need use some external library, for example Java Faker to generate random values. In this case, we should use testFixturesImplementation
to avoid to include the library on the final jar file.
project(':model') {
apply plugin: 'java-test-fixtures'
dependencies {
testFixturesImplementation('com.github.javafaker:javafaker:1.0.2')
}
}
Now test fixtures have access to that library.
/src/testFixtures/java/UserFixtures.java
|
|
I hope you find this setup handy to organise your test suite.
Do you want more? We invite you to subscribe to our newsletter to get the most relevan articles.
If you enjoy reading our blog, could you imagine how much fun it would be to work with us? let's do it!
But wait a second 🖐 we've got a conflict here. Newsletters are often 💩👎👹 to us. That's why we've created the LEAN LIST, the first zen, enjoyable, rocker, and reggaetoner list of the IT industry. We've all subscribed to newsletters beyond our limits 😅 so we are serious about this.