Akiner Alkan Akiner Alkan - 1 year ago 52
Java Question

How to write unit tests with parameters?

I am not familiar to java but in c#(NUnit) you can parameterize unit tests by adding

attribute as following:

public void DivideTest(int n, int d, int q)
Assert.AreEqual( q, n / d );

In this case we do not have to write seperate unit test for every test case. Instead we have writing [TestCase] to change the value.

Are there any equivelant on Java?
Currently using
Junit 4.12

Answer Source

Parameterized is what you need. Consider the below example. Note that test3 is obviously RED as 20/5 = 4.

import static org.junit.Assert.assertEquals;

import java.util.Arrays;
import java.util.Collection;

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

public class DividerTest {

  private int dividend;
  private int divisor;
  private int expectedResult;

  public static Collection<Object[]> data() {
    Object[] test1 = { 10, 5, 2 };
    Object[] test2 = { 15, 5, 3 };
    Object[] test3 = { 20, 5, 5 };

    return Arrays.asList(test1, test2, test3);

  public DividerTest(int dividend, int divisor, int expectedResult) {
    this.dividend = dividend;
    this.divisor = divisor;
    this.expectedResult = expectedResult;

  public void testDivider() {
    assertEquals(expectedResult, dividend / divisor);

And here are the test results:

enter image description here

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download