0

I am trying to unit test a function whose parameter is an exception. However, it seems that because the function only throws the exception and doesn't return in, I can't just feed a function and parameter that would throw an exception.

How can I deal with this?

user11039951
  • 141
  • 9

2 Answers2

-1

You can add a try-catch clause with the Exception you expect to be thrown, with a pass in the catch clause and a fail() after the catch clause.

Pim van Leeuwen
  • 293
  • 1
  • 9
-1

The major unit testing frameworks support verifying an exception.

Consider this method:

public boolean throwIfBlank(String input) {
    if(input == null || input.trim().isEmpty()) {
        throw new IllegalArgumentException("Input should not be blank.");
    }
    return true;
}

For JUnit 4, you could use the expected attribute of the @Test annotation to verify that an exception is thrown. If the exception is not thrown, then the unit test will be failed.

// JUnit 4
@Test( expected = IllegalArgumentException.class )
public void testBlankStringThrowsException() {
  classUnderTest.throwIfBlank("");
  // test will automatically fail if exception is NOT thrown
}

Similarly, in JUnit 5 you can explicitly assert that something is thrown using assertThrows:

@Test
void testBlankStringThrowsException() {
  assertThrows(IllegalArgumentException.class, () -> classUnderTest.throwIfBlank(""));
}

And finally, TestNG's @Test annotation supports a variety of attributes to verify that a particular exception is thrown:

@Test(
  expectedExceptions = IllegalArgumentException.class,
  expectedExceptionsMessageRegExp = "Input should not be blank."
)
public void testBlankStringThrowsException {
  classUnderTest.throwIfBlank("");
}

Of course, you can always wrap your test method in a try-catch block and explicitly call fail() if you do not throw the exception; generally this old-school method is not required but for completeness:

@Test
public void testBlankStringThrowsException() {
  try {
    classUnderTest.throwIfBlank("");
    fail("Blank string should have thrown an IllegalArgumentException!");
  } catch (IllegalArgumentException e) {
    // expected
  } catch (Exception e) {
    fail("Expected an IllegalArgumentException but threw: " + e);
  }
}
Roddy of the Frozen Peas
  • 14,380
  • 9
  • 49
  • 99