Jun 12, 2018

Create a Custom Annotation for your JUnit5 ParameterizedTest ArgumentProvider

In my opinion, the best new feature of Junit5 is the addition of parameterized tests. They greatly reduce copy/pasted code and makes it easy to increase your test coverage without unnecessarily increasing the amount of testing code you need to write and maintain.

Here is an example of a simple Parameterized Test that tests a variety of ints to see if they are divisible by 16

@ParameterizedTest
@ValueSource(ints = {24, 32, 48, 56, 64, 72, 80, 88, 96, 104, 112, 120, 128, 136, 144, 152, 160, 168, 176, 184, 192, 200})
void divisibleBy16(int i) {
    assertEquals(0, i % 16);
}

Now if we wanted to create a custom source for our test we could create our own ArgumentProvider…

 
public class OurCustomProvider implements ArgumentsProvider {
 
    public Stream provideArguments(ExtensionContext context) {
        return Stream.of(24, 32, 48, 56, 64, 72, 80, 88, 96, 104, 112, 120, 128, 136, 144, 152, 160, 168, 176, 184, 192, 200).map(Arguments::of);
    }
}

… and use it.

 
@ParameterizedTest
@ArgumentsSource(OurCustomProvider.class)
void divisibleBy16(int i) {
    assertEquals(0, i % 16);
}

Now we could settle for this but we don’t have to. We can upgrade our provider by making a custom annotation and use that instead of using the @ArgumentsSource and sending in our ArgumentProvider class. While we’re at it we’ll make it more generic so that its reusable for more of our tests.

First, let’s create our new annotation with some attributes, and annotate it as with an @ArgumentsSource of our ArgumentProvider (which we’ll write next).

import org.junit.jupiter.params.provider.ArgumentsSource;
 
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
 
@Target({ElementType.ANNOTATION_TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@ArgumentsSource(RangeArgumentsProvider.class)
public @interface RangeSource {
    int min() default 1;
 
    int max() default 100;
 
    int step() default 1;
}

Next, we have to create our argument provider. Implementing ArgumentsProvider as before and AnnotationConsumer to wire up our new Annotation.

import org.junit.jupiter.api.extension.ExtensionContext;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.ArgumentsProvider;
import org.junit.jupiter.params.support.AnnotationConsumer;
 
import java.util.stream.IntStream;
import java.util.stream.Stream;
 
public class RangeArgumentsProvider implements ArgumentsProvider, AnnotationConsumer {
    private int start;
    private int stop;
    private int step;
 
 
    RangeArgumentsProvider() {
    }
 
    public void accept(RangeSource source) {
        start = source.min();
        stop = source.max();
        step = source.step();
    }
 
    public Stream provideArguments(ExtensionContext context) {
        return IntStream.range(start, stop).filter(i -> (i - start) % step == 0).mapToObj(i -> Arguments.of(i));
    }
}

Now we can use our new custom annotation just like any of JUnit5’s built in argument providers like @ValueSource, @CsvSource, @MethodSource, etc.

@ParameterizedTest
@RangeSource(min = 24, max = 200, step = 8)
public void divisibleBy16(int i) {
    assertEquals(0, i % 16);
}

About the Author

Scott Bock profile.

Scott Bock

Principal Technologist

Scott is a Senior Software Engineer with over 12 years of experience using Java, and 5 years experience in technical leadership positions. His strengths include troubleshooting and problem solving abilities, excellent repertoire with customers and management, and verbal and written communication. He develops code across the entire technology stack including database, application, and user interface.

Leave a Reply

Your email address will not be published. Required fields are marked *

Related Blog Posts
Structuring SwiftUI Previews for API Calls
SwiftUI, together with Combine and Xcode 11+, provide a powerful toolset for quickly creating an app with a native UI. In Xcode 11+, the preview pane was introduced in order to provide live snapshots of […]
Seamlessly Integrating Micro Apps with iFrame
A recent client wanted to upgrade a small portion of their legacy application with a more modern UI and extra functionality, like fuzzy text search. There are a few approaches to incremental upgrades of legacy […]
Consul on Docker EE
[markdown]”Consul is a service networking solution to connect and secure services across any runtime platform and public or private cloud” – [https://consul.io](https://consul.io) This post details a way to run a Consul cluster on Docker EE […]
Passing the AWS Machine Learning Speciality Exam
The Amazon Machine Learning Specialty Exam is a 3-hour, 65 question test. It is designed to test your skills in AWS specific Data Engineering and Machine Learning Practices along with Machine Learning in general. I […]