How to do unit test for Exceptions?

后端 未结 5 815
时光取名叫无心
时光取名叫无心 2020-12-14 15:43

As you know, exception is thrown at the condition of abnormal scenarios. So how to analog these exceptions? I feel it is challenge. For such code snippets:

p         


        
5条回答
  •  不思量自难忘°
    2020-12-14 16:22

    Many unit testing frameworks allow your tests to expect exceptions as part of the test. JUnit, for example, allows for this.

    @Test (expected=IndexOutOfBoundsException.class) public void elementAt() {
        int[] intArray = new int[10];
    
        int i = intArray[20]; // Should throw IndexOutOfBoundsException
    }
    

提交回复
热议问题