How to do unit test for Exceptions?

后端 未结 5 821
时光取名叫无心
时光取名叫无心 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条回答
  •  猫巷女王i
    2020-12-14 16:12

    Okay there are a few possible answers here.

    Testing for an exception itself is easy

    import static org.hamcrest.core.Is.is;
    import static org.junit.Assert.assertThat;
    
    @Test
    public void TestForException() {
        try {
            doSomething();
            fail();
        } catch (Exception e) {
            assertThat(e.getMessage(), is("Something bad happened"));
        }
    }
    

    Alternately, you can use the Exception Annotation to note that you expect an exception to come out.

    Now, as to you specific example, Testing that something you are creating inside your method, either via new or statically as you did, when you have no way to interact with the object is tricky. You normally need to encapsulate that particular generator and then use some mocking to be able to override the behavior to generate the exception you expect.

提交回复
热议问题