Parameterization in Junit

Parameterization means running the same test with different inputs again and again inorder to check, if the expected output is displayed. With a short span of time we will be able to identify if the system is behaving as expected, when same code is run against different inputs.

What are the different sources we can store the parameterized test?
Different sources to store the parameterized test are

  1. Excel sheet
  2. CSV file
  3. Data base
  4. Collections

Let’s take an example on how parameterization works in Junit. Below are the steps to follow.

1.Declare the variables.
2.Call the parameterized constructor.
3.Pass the different inputs in a method.
4.Call the inputs declared in step 3 to another method.

Example : To print the details of student such as studentFirstName,studentLastName and studentID.

1.Declaring the variables :

public String studentFirstName;
public String studentLastName;
public int studentID;
2.Call the parameterized constructor.

public Parameterized_Junit(String studentFirstName, String studentLastName,int studentID)
{
this.studentFirstName=studentFirstName;
this.studentLastName=studentLastName;
this.studentID=studentID;
}
here the parameterized constructor is called by passing the parameters.
studentFirstName,studentLastName,studentID.

3.Pass the different inputs in a method.

@Parameters
public static Collection<Object[]> readData()
{
Object[][] data = new Object[2][3];

//1st row

data[0][0] =”john”;
data[0][1] =”smith”;
data[0][2]=45;

data[1][0] =”ken”;
data[1][1] =”sam”;
data[1][2]=87;

return Arrays.asList(data);

}
Here Junit’s @parameters annotation is used to differentiate from other methods, saying different inputs needs to be read from this method. All the inputs read will be returned in the form of Collections(list).

4.Call the inputs declared in step 3 to another method.

@Test
public void displayStudentInfo()
{
System.out.println(“Entered values–” + name+ “–“+ email_id+ “–“+ident_id);
}
Finally we are passing the inputs to the @Test script. Where in different inputs will be run against same set of code multiple times.

combining all the code and below is the complete set of code.


OUTPUT :

Leave a Comment

Your email address will not be published.