Why structure your integration tests ?
When the number of integration tests grow is a good practice to separate the tests based on the feature/api that they are testing.
The advantages of doing this are:
- easier to maitain as the tests for a specific feature/API are grouped in a specific category
- easier to run the tests only for that specific category when only that feature changes to get faster feedback
- easier to group the tests when running them in Jenkins/Travis CI or any other CI so that multiple jobs can be run in parallel and also when a job fails imediatelly the team will know which feature/API has failed
How is this done using Java, JUnit and Maven ?
- Create a basic Maven project
- Create a new package in the src/main/java with the name “tutorial.junit.categories” in which the different categories will be added.
The structure of the project should look like below: - Create a few JUnit test cases in a few test classes. In our case we are going to create:
- LoginApiTestIT.java
- SearchApiTestIT.java
- Create a few categories in which we want to split the tests. In our case we are going to split them as follows:
- LoginApiCategory – tests run against the login api
- SearchApiCategory – tests run against the search api
- SmokeTestCategory – which includes tests from either Login or Search API tests that we want to run as smoke tests
- A category is just an empty interface as in the example below:
- Setting the category for each of the tests. For setting the category we just need to add the @Category annotation either at the class or method level as below.
- Example below:
package tutorial.junit; import org.junit.Test; import org.junit.experimental.categories.Category; import tutorial.junit.categories.LoginApiCategory; import tutorial.junit.categories.SmokeTestCategory; @Category(LoginApiCategory.class) public class LoginApiTestIT { @Category(SmokeTestCategory.class) @Test public void shouldReturn200ForValidCredentials(){ System.out.println("Running Login API tests - Positive case"); } @Test public void shouldReturn404ForInvalidCredentials(){ System.out.println("Running Login API tests - Negative case"); } }
- Running the tests based on the category is pretty simple using the Maven commands below. Open the Maven pom.xml file location in your terminal and run the following commands:
- running the login tests
mvn clean install -P integration-test -Dgroups="tutorial.junit.categories.LoginApiCategory"
- running the search tests
mvn clean install -P integration-test -Dgroups="tutorial.junit.categories.SearchApiCategory"
- running the smoke tests which include tests from login and search
mvn clean install -P integration-test -Dgroups="tutorial.junit.categories.SmokeTestCategory"
- running the login tests