What is the purpose of when().thenReturn()
in Mockito, and why does it work this way?
I’m new to the Mockito library and struggling to understand the following syntax:
Before the test, I define:
when(CLASS.FUNCTION(PARAMETERS)).thenReturn(RETURN_VALUE);
And in the actual test:
assertSame(RETURN_VALUE, CLASS.FUNCTION(PARAMETERS));
Doesn’t the first line (when().thenReturn()
) just set the return value of the function to RETURN_VALUE
? If so, then of course, assertSame
will be true, and the test will pass.
What am I missing here? How does when().thenReturn()
actually work in Mockito?
You may be misunderstanding the role of when().thenReturn()
—it is used to specify how the mock behaves before calling the method under test.
The verification (assertSame()) ensures that the mocked method returns the expected value during the test.
Here’s how to resolve the confusion:
// Arrange: Define mock behavior
when(CLASS.FUNCTION(PARAMETERS)).thenReturn(RETURN_VALUE);
// Act: Call the method and capture the return value
Object result = CLASS.FUNCTION(PARAMETERS);
// Assert: Verify the returned value matches the mocked return value
assertSame(RETURN_VALUE, result);
This is necessary because the when().thenReturn()
line does not execute the method immediately; it simply configures the mock to return the desired value when the method is called during the test execution.
The assertion confirms that this behavior is correct.
If you are mocking a void method or need a slightly different mocking approach, you might use doReturn()
instead of when().thenReturn().
This is especially useful when dealing with void methods, or when you need to mock a method that throws exceptions.
Example with doReturn():
// Arrange: Mock behavior with doReturn for void methods
doReturn(RETURN_VALUE).when(mockedObject).someMethod();
// Act: Trigger the method call
Object result = mockedObject.someMethod();
// Assert: Check the returned result
assertSame(RETURN_VALUE, result);
This approach can be useful if you’re working with methods that don’t return values, or you need to mock specific exceptions.
You could also verify that the method is being called with specific parameters and count how many times it’s called. In this case, it’s not just about the returned value but ensuring that the interaction occurred correctly.
Example with verification:
// Arrange: Set mock behavior
when(CLASS.FUNCTION(PARAMETERS)).thenReturn(RETURN_VALUE);
// Act: Call the method
Object result = CLASS.FUNCTION(PARAMETERS);
// Assert: Verify the mock method was called
verify(CLASS, times(1)).FUNCTION(PARAMETERS);
// Assert: Check the returned value
assertSame(RETURN_VALUE, result);
In this solution, you’re not only verifying the return value but also checking that the mocked method was called exactly once with the specified parameters.