In JUnit4 you can write parameterized unit tests by providing parameters collection in one method, which will be passed to the constructor of the test and testing in another method. If I have a parameter for which I expect an exception to be thrown, how do I specify that?
In order to test the exception thrown by any method in JUnit 4, you need to use @Test(expected=IllegalArgumentException. class) annotation. You can replace IllegalArgumentException. class with any other exception e.g. NullPointerException.
this is how i use junit parameterized test with expected exceptions:
@RunWith(Parameterized.class) public class CalcDivTest { @Parameter(0) public int num1; @Parameter(1) public int num2; @Parameter(2) public int expectedResult; @Parameter(3) public Class<? extends Exception> expectedException; @Parameter(4) public String expectedExceptionMsg; @Rule public ExpectedException thrown = ExpectedException.none(); @Parameters public static Iterable<Object[]> data() { return Arrays.asList(new Object[][] { // calculation scenarios: { 120, 10, 12, null, null }, // simple div { 120, 0, -1, ArithmeticException.class, "/ by zero" }, // div by zero }); } @Test public void testDiv() throws CCalculationException { //setup expected exception if (expectedException != null) { thrown.expect(expectedException); thrown.expectMessage(expectedExceptionMsg); } assertEquals("calculation result is not as", expectedResult, div(num1, num2) ); } private int div(int a, int b) { return a/b; } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With