I have this in 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.
Why the thenReturn method doesn't return new 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.
If you need to provide an new instance, use thenAnswer
when(mockedMergeContext.createNewEntityOfType(IService.class))
.thenAnswer(new Answer() {
public IService answer(InvocationOnMock invocation) {
return new ServiceMock();
}
});