How do you assert that a certain exception is thrown in JUnit 4 tests?

前端 未结 30 1927
忘掉有多难
忘掉有多难 2020-11-21 22:23

How can I use JUnit4 idiomatically to test that some code throws an exception?

While I can certainly do something like this:

@Test
public void testFo         


        
30条回答
  •  甜味超标
    2020-11-21 22:55

    How about this: catch a very general exception, make sure it makes it out of the catch block, then assert that the class of the exception is what you expect it to be. This assert will fail if a) the exception is of the wrong type (eg. if you got a Null Pointer instead) and b) the exception wasn't ever thrown.

    public void testFooThrowsIndexOutOfBoundsException() {
      Throwable e = null;
    
      try {
        foo.doStuff();
      } catch (Throwable ex) {
        e = ex;
      }
    
      assertTrue(e instanceof IndexOutOfBoundsException);
    }
    

提交回复
热议问题