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
?
thenReturn(… .) method chain is used to specify a return value for a method call with pre-defined parameters. You also can use methods like anyString or anyInt to define that dependent on the input type a certain value should be returned.
thenAnswer( invocation -> { Object argument = invocation. getArguments()[1]; if (argument. equals(new ARequest(1, "A"))) { return new AResponse(1, "passed"); } else if (argument. equals(new ARequest(2, "2A"))) { return new AResponse(2, "passed"); } else if (argument.
Following are the differences between thenReturn and doReturn : * Type safety : doReturn takes Object parameter, unlike thenReturn . Hence there is no type check in doReturn at compile time. In the case of thenReturn , whenever the type mismatches during runtime, the WrongTypeOfReturnValue exception is raised.
In Mockito, you can specify what to return when a method is called. That makes unit testing easier because you don't have to change existing classes. Mockito supports two ways to do it: when-thenReturn and doReturn-when . In most cases, when-thenReturn is used and has better readability.
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<IService>() { public IService answer(InvocationOnMock invocation) { return new ServiceMock(); } });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With