How to mock void methods with Mockito

前端 未结 9 2094
情话喂你
情话喂你 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 12:58

    In Java 8 this can be made a little cleaner, assuming you have a static import for org.mockito.Mockito.doAnswer:

    doAnswer(i -> {
      // Do stuff with i.getArguments() here
      return null;
    }).when(*mock*).*method*(*methodArguments*);
    

    The return null; is important and without it the compile will fail with some fairly obscure errors as it won't be able to find a suitable override for doAnswer.

    For example an ExecutorService that just immediately executes any Runnable passed to execute() could be implemented using:

    doAnswer(i -> {
      ((Runnable) i.getArguments()[0]).run();
      return null;
    }).when(executor).execute(any());
    

提交回复
热议问题