DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Because the DevOps movement has redefined engineering responsibilities, SREs now have to become stewards of observability strategy.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Related

  • Why Testing is a Long-Term Investment for Software Engineers
  • JUnit, 4, 5, Jupiter, Vintage
  • Creating Your Swiss Army Knife on Java Test Stack
  • I Don’t TDD: Pragmatic Testing With Java

Trending

  • Distributed Consensus: Paxos vs. Raft and Modern Implementations
  • Optimizing Serverless Computing with AWS Lambda Layers and CloudFormation
  • Bridging UI, DevOps, and AI: A Full-Stack Engineer’s Approach to Resilient Systems
  • Is Big Data Dying?
  1. DZone
  2. Testing, Deployment, and Maintenance
  3. Testing, Tools, and Frameworks
  4. Readability in the Test: Exploring the JUnitParams

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.

By 
Otavio Santana user avatar
Otavio Santana
DZone Core CORE ·
Mar. 03, 23 · Tutorial
Likes (4)
Comment
Save
Tweet
Share
7.7K Views

Join the DZone community and get the full member experience.

Join For Free

Making 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.

Java
 
<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. 

Java
 
@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.

Java
 
@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.

Java
 
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:

Java
 
@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.


JUnit Testing Injection

Opinions expressed by DZone contributors are their own.

Related

  • Why Testing is a Long-Term Investment for Software Engineers
  • JUnit, 4, 5, Jupiter, Vintage
  • Creating Your Swiss Army Knife on Java Test Stack
  • I Don’t TDD: Pragmatic Testing With Java

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!