Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I test exceptions in a parameterized test?

Tags:

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?

like image 428
Gabriel Ščerbák Avatar asked Nov 11 '10 08:11

Gabriel Ščerbák


People also ask

How do you test when a method throws an exception?

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.


1 Answers

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; } } 
like image 86
Yarix Avatar answered Oct 12 '22 11:10

Yarix