0

I have a test case as

@Test(expected = IllegalArgumentException.class)
public void test() throws Exception{
  ..test content...
}

Because I'm using Java Reflection in my test case so the IllegalArgumentException is enwrapped in InvocationTargetException, how can I catch expected IllegalArgumentException instead of InvocationTargetException.

Error message shows as

java.lang.Exception: Unexpected exception, expected<java.lang.IllegalArgumentException> but was<java.lang.reflect.InvocationTargetException>
    at org.junit.internal.runners.statements.ExpectException.evaluate(ExpectException.java:28)
    at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
Neil
  • 2,714
  • 11
  • 29
  • 45
  • Problably the answer is already out there, but personally I would simply implement a custom hamcrest matcher that checks for the cause being an IllegalArgumentException - and then use the ExpectedException rule to use it. – Florian Schaetz Aug 07 '15 at 16:05

1 Answers1

1

I don't believe there's a JUnit way of doing it - you probably have to do it manually in the test, e.g.:

@Test
public void test() {
    try {
       runTest();
       fail();
    } catch (InvocationTargetException x) {
       if( ! (x.getCause() instanceof IllegalArgumentException)) {
           fail();
       }
    }
}
BarrySW19
  • 3,759
  • 12
  • 26