myborobudur
myborobudur

Reputation: 4435

Mockito thenReturn returns same instance

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?

Upvotes: 28

Views: 19126

Answers (3)

ptimson
ptimson

Reputation: 5803

In Java 8 with Lambdas you can just use

when(mockedMergeContext.createNewEntityOfType(IService.class)).thenAnswer(invocation -> new ServiceMock());

So just replace .thenReturn(new MyMock());

with .thenAnswer(invocation -> new MyMock());

Upvotes: 18

John B
John B

Reputation: 32949

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();
     }
   });

Upvotes: 66

Augusto
Augusto

Reputation: 29907

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.

Upvotes: 10

Related Questions