Readability in the Test: Exploring the JUnitParams
In this video tutorial, learn how to put more elegance in your test code by using JUnitParams. Learn types and how to simplify your tests with these techniques.
Join the DZone community and get the full member experience.
Join For FreeMaking the test readable and maintainable is a challenge for any software engineer. Sometimes, a test scope becomes even more significant when we need to create a complex object or receive information from other points, such as a database, web service, or property file. You can use simplicity by splitting the object creation from the test scope using the JUnitParams
. In this video tutorial, we'll learn how to use JUnitParams
, the types, and how to simplify your tests with these techniques.
The first question that might come to your mind is: "Why should I split the object from my test scope?" We'll start to enumerate some points and when this makes sense.
- Avoid the complexity: Eventually, you need to create instances that may vary with the context, so take this information from a database, microservices, and so on. To make it easier, you can divide and conquer, thus, moving away from this test.
- Define scope: To focus on the test or increase the cohesion of the test, you can split and receive the parameters from the injection.
The goal here is not to incentivize using this param injection on all tests, but once the parameters are complex and you need to test the same scenario with different tests are good candidates to explore it.
JUnitParams
is an extension that can help you in those cases. You need to add this dependency to your project. The code below shows the dependence on a Maven project.
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-params</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
With this dependency, we'll need to replace the conventional Test
annotation with ParameterizedTest
and tell the source where and how those parameters will be injected. In this post, we'll list three ways, all of those with annotations as follows:
ValueSource
: This source works with literal values directly on the annotation.MethodSource
: You can use methods on the class scope to feed this parameter.ArgumentSource
: If you wish, you can apply single responsibility here, where you can have a class to provide the arguments for the test.
To put it into practice, let's explore the soccer team scenario. We want to test the team business rule, where we need to ensure the team quantity, team's name, etc.
Let's start with the more accessible source, the ValueSource
. We can run the same test with different values. Another point is that with the ParameterizedTest
, you can define the test name using the parameter. Let's use it to test the team's name.
The code below shows the name
test, which should create a team
with the name
and match the value from the parameter. The test will run twice: you'll see two tests with different names.
@ParameterizedTest(name = "Should create a team with the name {0}")
@ValueSource(strings = {"Bahia", "Santos"})
public void shouldCreateTeam(String name) {
Team team = Team.of(name);
org.assertj.core.api.Assertions.assertThat(team)
.isNotNull().extracting(Team::name)
.isEqualTo(name);
}
The second source is the MethodSource
, where we can put more complex objects and create them programmatically. The return of this method uses the arguments that are an interface from JUnit.
The test below will test a Team
with a player
, where we'll check that given a player
, it will get into the team
.
@ParameterizedTest
@MethodSource("players")
public void shouldCreateTeamWithAPlayer(Player player) {
Assertions.assertNotNull(player);
Team bahia = Team.of("Bahia");
bahia.add(player);
org.assertj.core.api.Assertions.assertThat(bahia.players())
.hasSize(1)
.map(Player::name)
.contains(player.name());
}
static Collection<Arguments> players() {
return List.of(Arguments.of(Player.of("Neymar", "Santos", 11)));
}
The last one we'll explore today is ArgumentSource
, where you can have a class to focus on providing these arguments. The third and final test will create it. We'll test the sum of scores in a soccer team.
The first step is to create a class that implements the ArgumentsProvider
interface. This interface receives a context-param
where you can reveal helpful information such as tags and display names. Thus, use it such as if the tag is "database," and take the source from the database. In our first test, we won't use it.
public class PlayerProvider implements ArgumentsProvider {
@Override
public Stream<? extends Arguments> provideArguments(ExtensionContext extensionContext) throws Exception {
List<Player> players = new ArrayList<>();
players.add(Player.of("Poliana", "Salvador", 20));
players.add(Player.of("Otavio", "Salvador", 0));
return Stream.of(Arguments.of(players));
}
}
The first step is to use it on the source, which is pretty similar to other sources using the annotation:
@ParameterizedTest
@ArgumentsSource(PlayerProvider.class)
public void shouldCreateTotalScore(List<Player> players) {
Team team = Team.of("Leiria");
players.forEach(team::add);
int score = team.score();
int playerScore = players.stream().mapToInt(Player::score)
.sum();
Assertions.assertEquals(playerScore, score);
}
That is it!
The video below aims to explore more of the capability of injecting parameters in the test using JUnitParams
. The three source types are just the beginning. I hope that inspires you to make your code readable with the param
capability.
Opinions expressed by DZone contributors are their own.
Comments