問題描述
我在 Mockito 中有這個:
I have this in Mockito:
when(mockedMergeContext.createNewEntityOfType(IService.class)).thenReturn(new ServiceMock());
createNewEntityOfType
方法應該總是返回一個新的 ServiceMock
實例,但它會返回兩次相同的引用.
The createNewEntityOfType
method should always return a new ServiceMock
instance but it returns twice the same reference.
為什么 thenReturn
方法沒有返回新的 ServiceMock
?
Why the thenReturn
method doesn't return new ServiceMock
?
推薦答案
thenReturn
方法將始終返回傳遞給它的內容.new Servicemock()
代碼在調用 thenReturn
之前被執行.然后將創建的 ServiceMock
傳遞給 thenReturn
.因此 thenReturn
具有 ServiceMock
的絕對實例,而不是創建機制.
The thenReturn
method will always return what is passed to it. The code new Servicemock()
is being executed prior to the call to thenReturn
. The created ServiceMock
is then being passed to thenReturn
. Therefore thenReturn
has a absolute instance of ServiceMock
not a creation mechanism.
如果您需要提供新實例,請使用 thenAnswer
If you need to provide an new instance, use thenAnswer
when(mockedMergeContext.createNewEntityOfType(IService.class))
.thenAnswer(new Answer<IService>() {
public IService answer(InvocationOnMock invocation) {
return new ServiceMock();
}
});
這篇關于Mockito thenReturn 返回相同的實例的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!