JUnit testing with multiple test cases in a method

java, junit, mockito, unit-testing

Solution

Use a Parameterized runner test.

@RunWith(Parameterized.class)
public class ATest {
    private String value1;
    private String value2;

    private static final String ABC = "abc";
    private static final String XYZ = "xyz";

    public ATest(String value1, String value2) {
        this.value1 = value1;
        this.value2 = value2;
    }

    @Test(expected=NullPointerException.class)
    public void nullPassedToConstructor() {
         A a = new A(value1, value2);
    }

    // Provide data
    @Parameters
    public static List<Object[]> data() {
    List<Object[]> list = new ArrayList<Object[]>();

        list.add(new Object[] {null, XYZ});
        list.add(new Object[] {ABC, null});
        list.add(new Object[] {null, null});

        return list;
    }
}

Problem

I have a following class A with a constructor that takes two strings as parameters. ``` Class A { String test1; String test2; public(String test1, String test2) { this.test1 = test1; this.test2 = test2; } } ``` I would like to test a constructor with three test cases within a one test case method i.e. 1. Null test1 2. Null test2 3. Null test1, Null test2 ``` String test1 = "ABC"; String test2 = "XYZ"; @Test(expected=NullPointerException.class) public void testNullConstructorValues() { new A(null, test2); new A(test1, null); new A(null, null); } ``` The problem here is that after first constructor declaration, the method throws NPE and returns out of the method. I would like the method to execute all 3 constructor declarations within just one method and perform the expected exception check. Is there any way to do this of doing all 3 test cases within one method?

Original source