I wonder how I can write test for particular exception assertion?
For example (my 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 assert exception, or I need to model situation in concrete test-method?
Before JUnit 4.7, it wasn't possible to use data-driven testing like this, where some data combinations produce exceptions and some don't.
It is possible to create two different data-driven tests, where all the combinations in one don't produce exceptions, and all the combinations in the other do produce exceptions.
Use the
@Test(expected=YourException.class)
for the tests that expect exceptions, unless you need extra test logic. Theexpected
annotation parameter isn't very powerful.Since 4.7, there's been an
@Rule
that works for it. See @eee's answer for details.