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

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

    Take for example, you want to write Junit for below mentioned code fragment

    public int divideByZeroDemo(int a,int b){
    
        return a/b;
    }
    
    public void exceptionWithMessage(String [] arr){
    
        throw new ArrayIndexOutOfBoundsException("Array is out of bound");
    }
    

    The above code is to test for some unknown exception that may occur and the below one is to assert some exception with custom message.

     @Rule
    public ExpectedException exception=ExpectedException.none();
    
    private Demo demo;
    @Before
    public void setup(){
    
        demo=new Demo();
    }
    @Test(expected=ArithmeticException.class)
    public void testIfItThrowsAnyException() {
    
        demo.divideByZeroDemo(5, 0);
    
    }
    
    @Test
    public void testExceptionWithMessage(){
    
    
        exception.expectMessage("Array is out of bound");
        exception.expect(ArrayIndexOutOfBoundsException.class);
        demo.exceptionWithMessage(new String[]{"This","is","a","demo"});
    }
    

提交回复
热议问题