How to mock void methods with Mockito

前端 未结 9 2234
情话喂你
情话喂你 2020-11-22 12:21

How to mock methods with void return type?

I implemented an observer pattern but I can\'t mock it with Mockito because I don\'t know how.

And I tried to fin

9条回答
  •  旧巷少年郎
    2020-11-22 13:08

    First of all: you should always import mockito static, this way the code will be much more readable (and intuitive):

    import static org.mockito.Mockito.*;
    

    For partial mocking and still keeping original functionality on the rest mockito offers "Spy".

    You can use it as follows:

    private World world = spy(new World());
    

    To eliminate a method from being executed you could use something like this:

    doNothing().when(someObject).someMethod(anyObject());
    

    to give some custom behaviour to a method use "when" with an "thenReturn":

    doReturn("something").when(this.world).someMethod(anyObject());
    

    For more examples please find the excellent mockito samples in the doc.

提交回复
热议问题