How to mock void methods with Mockito

前端 未结 9 2206
情话喂你
情话喂你 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:18

    Adding to what @sateesh said, when you just want to mock a void method in order to prevent the test from calling it, you could use a Spy this way:

    World world = new World();
    World spy = Mockito.spy(world);
    Mockito.doNothing().when(spy).methodToMock();
    

    When you want to run your test, make sure you call the method in test on the spy object and not on the world object. For example:

    assertEquals(0, spy.methodToTestThatShouldReturnZero());
    

提交回复
热议问题