[英]Mockito thenReturn returns same instance
I have this in Mockito: 我在Mockito有这个:
when(mockedMergeContext.createNewEntityOfType(IService.class)).thenReturn(new ServiceMock());
The createNewEntityOfType
method should always return a new ServiceMock
instance but it returns twice the same reference. createNewEntityOfType
方法应始终返回一个新的ServiceMock
实例,但它返回两次相同的引用。
Why the thenReturn
method doesn't return new ServiceMock
? 为什么thenReturn
方法不返回新的ServiceMock
?
The thenReturn
method will always return what is passed to it. thenReturn
方法将始终返回传递给它的内容。 The code new Servicemock()
is being executed prior to the call to thenReturn
. new Servicemock()
代码在调用thenReturn
之前执行。 The created ServiceMock
is then being passed to thenReturn
. 然后将创建的ServiceMock
传递给thenReturn
。 Therefore thenReturn
has a absolute instance of ServiceMock
not a creation mechanism. 因此, thenReturn
具有ServiceMock
的绝对实例而不是创建机制。
If you need to provide an new instance, use thenAnswer 如果您需要提供新实例,请使用thenAnswer
when(mockedMergeContext.createNewEntityOfType(IService.class))
.thenAnswer(new Answer<IService>() {
public IService answer(InvocationOnMock invocation) {
return new ServiceMock();
}
});
You might want to refactor that into different statements to understand why that happens. 您可能希望将其重构为不同的语句,以了解发生这种情况的原因。
Service svc = new ServiceMock();
when(mockedMergeContext.createNewEntityOfType(IService.class)).thenReturn( svc );
Do you see now why it doesn't work? 你现在看到为什么它不起作用? :) :)
It's always returning the instance hold in svc, it won't re-evaluate new ServiceMock()
each time that the method is invoked. 它始终在svc中返回实例保持,每次调用该方法时都不会重新评估new ServiceMock()
。
In Java 8 with Lambdas you can just use 在使用Lambdas的Java 8中,您可以使用
when(mockedMergeContext.createNewEntityOfType(IService.class)).thenAnswer(invocation -> new ServiceMock());
So just replace .thenReturn(new MyMock());
所以只需替换.thenReturn(new MyMock());
with .thenAnswer(invocation -> new MyMock());
with .thenAnswer(invocation -> new MyMock());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.