問題描述
我在 Mockito 中有這個(gè):
I have this in Mockito:
when(mockedMergeContext.createNewEntityOfType(IService.class)).thenReturn(new ServiceMock());
createNewEntityOfType
方法應(yīng)該總是返回一個(gè)新的 ServiceMock
實(shí)例,但它會(huì)返回兩次相同的引用.
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
方法將始終返回傳遞給它的內(nèi)容.new Servicemock()
代碼在調(diào)用 thenReturn
之前被執(zhí)行.然后將創(chuàng)建的 ServiceMock
傳遞給 thenReturn
.因此 thenReturn
具有 ServiceMock
的絕對實(shí)例,而不是創(chuàng)建機(jī)制.
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.
如果您需要提供新實(shí)例,請使用 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();
}
});
這篇關(guān)于Mockito thenReturn 返回相同的實(shí)例的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!