When should I use Mockito's doAnswer versus thenReturn?

I’m using Mockito for service layer unit testing and I’m trying to understand the differences between doAnswer and thenReturn. When should I use doAnswer versus thenReturn? I’ve primarily used thenReturn so far, but I’m unsure when doAnswer might be more appropriate. Can someone explain the details of using mockito doanswer?

Hey Shreshthaseth,

Returning Values from a Mock thenReturn: Use thenReturn when you need to specify a fixed return value for a method call. It’s straightforward and ideal for simple cases where the method being mocked should return a specific value.

when(mock.someMethod()).thenReturn(“fixed value”); Example: If you have a method getUserName that should always return “John Doe”, use thenReturn:

when(mock.getUserName()).thenReturn(“John Doe”);

Hey Shreshthaseth,

Handling Multiple Calls with Different Results : thenReturn: You can use thenReturn with multiple arguments to return different values on successive calls. This is useful when you want to simulate varying responses.

when(mock.someMethod()).thenReturn(“first value”, “second value”, “third value”);

doAnswer: Use doAnswer when you need to execute custom logic or return different values based on the input or call context. It provides more flexibility than thenReturn. doAnswer(invocation → { Object[] args = invocation.getArguments(); return "value based on " + args[0]; }).when(mock).someMethod(anyString());

Example: If getUserRole should return different roles based on the input, you can use doAnswer:

doAnswer(invocation → { String role = (String) invocation.getArguments()[0]; return "Role for " + role; }).when(mock).getUserRole(anyString());