0

Is there any difference between these two lines of code?

Option 1:

doReturn(masterQuery).when(tldSpy).makeMyInsightAPIQuery(anyString());

Option 2:

stub(tldSpy.makeMyInsightAPIQuery(anyString())).toReturn(masterQuery);

Someone else asked a similar question (Mockito - difference between doReturn() and when()) but I'm asking about toReturn() which was not addressed in that question.

Community
  • 1
  • 1
Michael Osofsky
  • 11,429
  • 16
  • 68
  • 113

1 Answers1

1

stub(T).toReturn(...) is just a deprecated syntax replaced by when(T).thenReturn(...). Same rules and guidelines apply as in the question you linked:

  • when().thenReturn() and stub().toReturn() can do return type checking
  • doAnswer().when() is the only way to stub void methods
  • doReturn().when() avoids calling the real method in spies and already-stubbed objects

Otherwise, they have exactly the same behavior and the same consequences, and can be used interchangeably.

Community
  • 1
  • 1
Jeff Bowman
  • 90,959
  • 16
  • 217
  • 251