2011-08-31 86 views
7

如果我嘲笑一種方法來返回某個對象的新實例,我該如何捕獲返回的實例?mockito:有沒有一種方法來捕獲stubbed方法的返回值?

例如爲:

when(mock.someMethod(anyString())).thenAnswer(new Answer() { 
    Object answer(InvocationOnMock invocation) { 
     Object[] args = invocation.getArguments(); 
     Object mock = invocation.getMock(); 
     return new Foo(args[0]) 
    } 
}); 

很顯然,我可以有Foo類型的字段,而裏面answer其設置到新的實例,但有一個更好的辦法嗎?像ArgumentCaptor?

回答

6

看起來要觀察然後Answer實例和接收notfications每個answer方法被調用的時候(這將觸發新Foo創建)。那麼,爲什麼不發明一種ObservableAnswer類:

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); 
} 

用途:

Listener[] myListenerns = 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]) 
    } 

}); 
9

我想要做類似的事情,但有窺探的對象,而不是模仿。具體來說,給定一個窺探對象,我想捕獲返回值。根據Andreas_D的回答,這是我想出來的。

public class ResultCaptor<T> implements Answer { 
    private T result = null; 
    public T getResult() { 
     return result; 
    } 

    @Override 
    public T answer(InvocationOnMock invocationOnMock) throws Throwable { 
     result = (T) invocationOnMock.callRealMethod(); 
     return result; 
    } 
} 

預期用法:

// spy our dao 
final Dao spiedDao = spy(dao); 
// instantiate a service that does some stuff, including a database find 
final Service service = new Service(spiedDao); 

// let's capture the return values from spiedDao.find() 
final ResultCaptor<QueryResult> resultCaptor = new ResultCaptor<>(); 
doAnswer(resultCaptor).when(spiedDao).find(any(User.class), any(Query.class)); 

// execute once 
service.run(); 
assertThat(resultCaptor.getResult()).isEqualTo(/* something */); 

/// change conditions /// 

// execute again 
service.run(); 
assertThat(resultCaptor.getResult()).isEqualTo(/* something different */); 
相關問題