Mockito verify after exception Junit 4.10

前端 未结 4 1150
没有蜡笔的小新
没有蜡笔的小新 2020-12-05 22:19

I am testing a method with an expected exception. I also need to verify that some cleanup code was called (on a mocked object) after the exception is thrown, but it looks li

4条回答
  •  南方客
    南方客 (楼主)
    2020-12-05 23:11

    Once Exception is thrown in UT, all the code below that will be ignored.

    @Test(expected = Exception.class)
    public void testExpectedException() {
       MockedObject mockObj = mock(MockedObj.class);
       MySubject subject = new MySubject(mockedObj);
       subject.doSomething(); // If this line results in an exception then all the code below this will be ignored.
       subject.someMethodThrowingException();
       verify(mockObj).
           someCleanup(eq(...));
    }
    

    To counter this and verify all the calls made, we can use try with finally.

    @Test(expected = Exception.class)
        public void testExpectedException() {
              MockedObject mockObj = mock(MockedObj.class);
              MySubject subject = new MySubject(mockedObj);
              try {
                   subject.someMethodThrowingException(); 
              } finally {
                 verify(mockObj).
                 someCleanup(eq(...));
              }
    } 
    

提交回复
热议问题