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

前端 未结 30 1999
忘掉有多难
忘掉有多难 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:00

        @Test(expectedException=IndexOutOfBoundsException.class) 
        public void  testFooThrowsIndexOutOfBoundsException() throws Exception {
             doThrow(IndexOutOfBoundsException.class).when(foo).doStuff();  
             try {
                 foo.doStuff(); 
                } catch (IndexOutOfBoundsException e) {
                           assertEquals(IndexOutOfBoundsException .class, ex.getCause().getClass());
                          throw e;
    
                   }
    
        }
    

    Here is another way to check method thrown correct exception or not.

提交回复
热议问题