mockito: Is there a way of capturing the return value of stubbed method?

前端 未结 3 1216
旧时难觅i
旧时难觅i 2021-02-12 12:51

If I mock a method to return a new instance of some object, how can I capture the returned instance?

E.g.:

 when(mock.someMethod(anyString())).thenAnswe         


        
3条回答
  •  花落未央
    2021-02-12 13:34

    Looks like you want to observe and then Answer instances, and receive notifications each time the answer method is called (which triggers the creation of a new Foo). So why not invent an ObservableAnswer class:

    public abstract class ObservableAnswer implements Answer {
      private Listener[] listeners; // to keep it very simple...
    
      public ObservableAnswer(Listener...listeners) {
        this.listeners = listeners;
      }
    
      @Override
      public Object answer(InvocationOnMock invocation) {
        Object answer = observedAnswer(invocation);
        for (Listener listener:listeners) {
           listener.send(answer);
        }
        return answer;
      }
    
      // we'll have to implement this method now
      public abstract Object observedAnswer(InvocationOnMock invocation);
    }
    

    Intended use:

    Listener[] myListeners = getListeners();  // some magic (as usual)
    when(mock.someMethod(anyString())).thenAnswer(new ObservableAnswer(myListeners) {
         Object observedAnswer(InvocationOnMock invocation) {
             Object[] args = invocation.getArguments();
             Object mock = invocation.getMock();
             return new Foo(args[0])
         }
    
     });
    

提交回复
热议问题