Java - Junit - Parametrized Test

Eclipse Oepe Junit Library

About

Java - JUnit

When running a parameterized test class, test object instances are created for the cross-product of:

  • the test methods
  • and the test data elements.

Then for instance, for 2 test methods with two data elements, will become 4 instances.

Code

package com.gerardnico.junit;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;

import java.util.Arrays;

import static org.junit.Assert.assertEquals;

/**
 * Created by gerard on 29-05-2016.
 */
@RunWith(value = Parameterized.class)
public class ParametersTest {

    // This function will call the constructor for each element of its array
    // 
    // The set of test (and/of parameters) are then declared below
    // The name argument below will be present in the Junit output
    @Parameterized.Parameters(name = "{index}: add({0}-{1})={2}")
    public static Iterable<Object[]> data1() {
        return Arrays.asList(new Object[][]{
                {1, 1, 0},
                {2, 2, 0},
                {8, 2, 6},
                {4, 5, -1}
        });
    }

    // The constructor get called for each row of the array defined above 
    // where the Parameters are the value of each element in a row
    public ParametersTest(int numberA, int numberB, int expected) {
        this.numberA = numberA;
        this.numberB = numberB;
        this.expected = expected;
    }

    
    // Variable that will hold the value
    // for each test (ie for each row)
    private int numberA;
    private int numberB;
    private int expected;


    @Test
    public void test_substraction() {
        assertEquals(expected, numberA - numberB);
    }


}

Output:

  • 0 ms

    [0: add(1-1)=0]

  • 0 mspassed

    test_substraction[0: add(1-1)=0]

  • 0 ms

    [1: add(2-2)=0]

  • 0 mspassed

    test_substraction[1: add(2-2)=0]

  • 0 ms

    [2: add(8-2)=6]

  • 0 mspassed

    test_substraction[2: add(8-2)=6]

  • 0 ms

    [3: add(4-5)=-1]

  • 0 mspassed

    test_substraction[3: add(4-5)=-1]

  • Documentation / Reference





    Discover More
    Eclipse Oepe Junit Library
    Java - JUnit

    Written by Erich Gamma (of Design Patterns fame) and Kent Beck (creator of XP methodology) A simple framework to write and run repeatable tests JUnit features include: Assertions for testing expected...



    Share this page:
    Follow us:
    Task Runner