Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 896
myborobudur Avatar asked Nov 22 '11 13:11

myborobudur


People also ask

What does thenReturn do in Mockito?

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.

How do you mock the same method with different parameters?

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.

What is the difference between doReturn and thenReturn in Mockito?

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.

How do I return an object in Mockito?

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.


1 Answers

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();      }    }); 
like image 104
John B Avatar answered Sep 30 '22 19:09

John B