Mockito test a void method throws an exception

后端 未结 2 1273
抹茶落季
抹茶落季 2020-11-30 16:58

I have a method with a void return type. It can also throw a number of exceptions so I\'d like to test those exceptions being thrown. All attempts have failed w

相关标签:
2条回答
  • 2020-11-30 17:27

    If you ever wondered how to do it using the new BDD style of Mockito:

    willThrow(new Exception()).given(mockedObject).methodReturningVoid(...));
    

    And for future reference one may need to throw exception and then do nothing:

    willThrow(new Exception()).willDoNothing().given(mockedObject).methodReturningVoid(...));
    
    0 讨论(0)
  • 2020-11-30 17:41

    The parentheses are poorly placed.

    You need to use:

    doThrow(new Exception()).when(mockedObject).methodReturningVoid(...);
                                              ^
    

    and NOT use:

    doThrow(new Exception()).when(mockedObject.methodReturningVoid(...));
                                                                       ^
    

    This is explained in the documentation

    0 讨论(0)
提交回复
热议问题