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

前端 未结 30 1956
忘掉有多难
忘掉有多难 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 23:15

    JUnit 5 Solution

    @Test
    void testFooThrowsIndexOutOfBoundsException() {    
      Throwable exception = expectThrows( IndexOutOfBoundsException.class, foo::doStuff );
    
      assertEquals( "some message", exception.getMessage() );
    }
    

    More Infos about JUnit 5 on http://junit.org/junit5/docs/current/user-guide/#writing-tests-assertions

提交回复
热议问题