Make sure some parameterized vectors will throw an exception in JUnit?

I wonder how I can write a test for a specific exception statement?

For example, (test data container):

@Parameters(name = "{index}: {0} > {1} > {2} > {3} > {4}")
public static Iterable<Object[]> data() {
  return Arrays.asList(new Object[][] {
    {"1200", new byte[] {0x4B0}, "1200", 16, 2},
    {"10", new byte[] {0x0A}, "10", 8, 1},
    {"13544k0", new byte[] {0x0A}, "1200", 8, 1},  <== assert thrown exception
    {"132111115516", new byte[] {0x0A}, "1200", 8, 1},<== assert thrown exception
  });
}

Is it possible to use such container data to state an exception, or do I need to model the situation in a specific test method?

+4
source share
3 answers

Prior to JUnit 4.7, it was not possible to use data testing like this when some combinations of data throw exceptions and some don't.

, , , .

@Test(expected=YourException.class) , , . expected .

4.7, @Rule. . @eee.

+6

JUnit ExpectedException, :

@RunWith(Parameterized.class)
public class MyParameterizedTest {

    public class UnderTest {
        public void execute(String input) {
            if ("1".equals(input)) {
                throw new RuntimeException();
            }
        }
    }

    @Rule
    public ExpectedException expected = ExpectedException.none();

    @Parameters(name = "{index}: {0}")
    public static Iterable<Object[]> data() {
        return Arrays.asList(new Object[][] {
                    {"1", RuntimeException.class},
                    {"2", null}    
        });
    }

    @Parameter(value = 0)
    public String input;

    @Parameter(value = 1)
    public Class<Throwable> exceptionClass;

    @Test
    public void test() {
        if (exceptionClass != null) {
            expected.expect(exceptionClass);
        }

        UnderTest underTest = new UnderTest();          
        underTest.execute(input);
    }
}
+6

. , , ? . , , . 2 - ,

2 , , , @eee, /

+1
source

All Articles