0

I would like to create a JUnit Test Case that creates a case for every iteration of an array. How do I go about doing this? I've seen some docs about @Parameterized.Parameters but it seems like I will need to reconstruct my original array to look like {{array[0], constantValue}, {array[1], constantValue}}. Is there any way I can get JUnit to do the following:

public class Testing {

String[] array;
String constantValue;

@Test
public void test_arrayValue0() {
   assertEquals(array[0] + " is true", true, method(array[0], constantValue));
}

@Test
public void test_arrayValue1() {
   assertEquals(array[1] + "is true", true, method(array[1], constantValue));
}


@Test
public void test_arrayValue2() {
   assertEquals(array[2] + " is true", true, method(array[2], constantValue));
}
//..until array is complete
}

1 Answer 1

3

You need to parameterize your test with the array values (and optionally indices):

@RunWith(Parameterized.class)
public class Testing {
    private final static String constantValue = "myConstant";

    @Parameters
    public static Object[][] params() { 
         return new Object[][]{ 
                new Object[] { "item0", 0 },
                new Object[] { "item1", 1 },
                //...
         };
    }

    @Param(0)
    public String arrayValue;

    @Param(1)
    public int arrayIndex;

    @Test
    public void test_arrayValue() {
        assertEquals("array" + arrayIndex + " is true", true, method(arrayValue, constantValue));
    }
}

Then your test_arrayValue will be called as many times as you supplied parameters, each time with your next pair of index and value you specified.

Alternatively, you can define you array just a field:

private final String[] array = new String[] {"item0", "item1", ... }

And then parameterize your test with an index only.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.