Parameterized Tests In Junit

Reading Time: 2 minutes

1. Overview

So Basically this feature enables us to execute a single test method multiple times with different parameters.In this blog i am going to explore parameterized Tests in depth ,so let’s get started

2. Dependencies

In order to use Junit parameterized test first we need to add the dependencies for that if we have maven project then we need to add the maven dependencies for Junit parameterized test and if we are using the gradle project then we need to add the gradle dependencies for that ,we add the dependencies in Pom.xml file,so the dependencies of maven and gradle are in the following ways.

a) Maven Dependency

<dependency>

<groupId>org.junit.jupiter</groupId>

<artifactId>junit-jupiter-params</artifactId>

<version>5.8.1</version>

<scope>test</scope>

</dependency>

b) Gradle Dependency

testCompile(“org.junit.jupiter:junit-jupiter-params:5.8.1”)

3. First Impression 

Let suppose we have a method and we would like to be confident about its behaviour:-

public class Math{

public static boolean checkWhetherNumberIsEven(int number){

return number%2==0;

}

}

we can say that parameterized tests are similar to another test but what make them different to another test is there’s annotation ,so whenever we will use parameterized test we have to add @ParameterizedTest annotation

@ParameterizedTest

@ValueSource(ints ={2,4,6,8}) //four numbers

void checkWheteherNumberIsEvenShouldReturnEven(int number){

assertTrue(Math.checkWhetherNumberIsEven(number));

}

JUnit 5 test runner executes this above test — and consequently, the checkWhetherNumberIsEven method — four times. And each time, it assigns a different value from the @ValueSource array to the number method parameter.

So, this example shows us two things we need for a parameterized test:

a source of arguments, in this case, an int array

a way to access them, in this case, the number parameter

Conclusion:-

In this blog we have explored the parameterized test,We learned that parameterized tests are different from normal tests in two aspects: they’re annotated with the @ParameterizedTest, and they need a source for their declared arguments.

Refrences:-

https://junit.org/junit5/docs/current/user-guide/


Knoldus-blog-footer-image

Written by 

Hi Guys This is Jatin, I am working as Java Consultant in Knoldus Software LLP. I like to explore new technology and learn from the java community blogs.