Tuesday, 21 December 2010

Java: Parameterized unit tests with JUnit

JUnit is a unit testing framework for the Java programming language.In this article I will explain how to create test with predefined values.This feature works in JUnit 4.

Structure of a parameterized test class

To mark a test class as a parameterized test, you must first annotate it with @RunWith(Parameterized.class). The class must then provide at least three entities:
  1. A static method that generates and returns test data,
  2. A constructor that stores the test data
  3. A test
The method that generates test data must be annotated with @Parameters, and it must return a Collection of Arrays.

How it's work 
Values from  static method goes in our constructor and instantiate class over and over.(Number of parameters in constructor should correspond to the number of parameters in each array)

Example
I this example test will check does 1 + 4 =5 and other, all data it will take from array.

//tested class
public class Counter {
 private double x;
 private double y;
 
 public Counter(double x, double y){
  this.x = x;
  this.y = y;
 }
        public double addXandY(){
  return x + y;
 }
}

import java.util.Arrays;
import java.util.Collection;
import org.junit.Test;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
import org.junit.runner.RunWith;
import static org.junit.Assert.*;

@RunWith(Parameterized.class)
public class ParameterizedTestExample {

 private double number;
 private double number2;
 private double result;
 private Counter coun;

        //constructor takes parameters from array 
 public ParameterizedTestExample(double number, double number2,
   double result1) {
  this.number = number;
  this.number2 = number2;
  this.result = result1;
  coun = new Counter(number, number2);
 }

  //array with parameters
  @Parameters
  public static Collection<Object[]> data() {
      Object[][] data = new Object[][] { { 1, 4, 5 }, { 2, 7, 9 },
           { 3, 7, 10 }, { 4, 9, 13 } };
 return Arrays.asList(data);
 }
   //running our test     
   @Test
   public void testCounter() {
 assertEquals("Result add x y", result, coun.addXandY(), 0);
   }
}
 

1 comment:

  1. You can have a look at TestNG (http://testng.org/). TestNG allows you to annotate a method with @DataProvider annotation to supply the values you need to test. More details here:
    http://testng.org/doc/documentation-main.html#parameters-dataproviders

    ReplyDelete