Maarten van Heek
Maarten van Heek

Reputation: 45

JUnit test expected exception with multiple (different) arguments

I have a Java program with an Address class that should contain a zip/postal code, with basically the format \d{4}[A-Z]{2}. This code throws a custom (checked) IncorrectPostcodeException, and I want to test this with JUnit. Looking at other questions I found out how to test if the right exception is indeed thrown.

I now want to run the test with multiple arguments. To make sure the test works as expected, I included a 'wrong' postcode as well so the test should fail. If I attempt this with a regular method, it works as expected, and the below test fails because the seconde postcode is NOT correct.

@Test
public void testPostcode() throws IncorrectPostcodeException {
Address correctPostcode = new Address();
correctPostcode.setPostcode("1234AB");
correctPostcode.setPostcode("12"); // THIS SHOULD FAIL THE TEST
}

However, if I write an exception test in a similar manner, the test does NOT fail:

@Test(expected=IncorrectPostcodeException.class)
public void testPostcodeException() throws IncorrectPostcodeException {
Address wrongPostcode = new Address();
System.out.println("1");
wrongPostcode.setPostcode("123AB"); // throws exception as expected
System.out.println("2");
wrongPostcode.setPostcode("1234AB"); //THIS SHOULD FAIL THE TEST
System.out.println("3");
wrongPostcode.setPostcode("123ABC"); // should throw exception too but is not reached
}

If I put this second postcode as the first or only testcase, the test fails as expected. But the println statements, added for 'debugging', indeed show that only the first line is executed.

How do I make JUnit test an exception with multiple input arguments, without writing individiual methods for each test case? I looked for answers, but other questions seem to be concerned with testing multiple different exceptions in one method, not multiple arguments for one exception.

Upvotes: 1

Views: 924

Answers (1)

GaspardP
GaspardP

Reputation: 890

In your test, you are throwing an exception with "123AB". And the test ends here. The others methods (set post codes with other data, system out...) are not executed.

If you want to check the other cases, they should be in other tests cases.

You could try to do 2 parametrized tests, one with all the failling cases, and one with all the exceptions.

Upvotes: 0

Related Questions