Mockito when().thenReturn() Use this.equal(other) to Match the Parameter

Mockito has


So if the following is called

Mockito will try to control and determine whether to return the specified result, then how? I was a bit confused by this and I thought it probably need exactly the same object to pass to in order to get the result. That is, whether return the specified result is determined whether the actual parameter passed to is the same as the one in when().thenReturn statement against specified and the question is how does it actually happen.

What actually happens is that this is tested by


NOT by the following

specified == actual.

This indicates that we do not have to pass the same object if we want some controlled behavior, as long as the passed objects has the same content and is equal to the specified one, then the returned results would be the one we specified in when().theReturn() statement. The following code could pass the test and thus verified this and resolves my previous confusion.


import static org.junit.Assert.*;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import static org.mockito.Mockito.*;

public class AppTest
	Rabbit fixture;

	public void shouldTestEat() {
		String goodCase = new String("bcccc");
		String goodCase2 = new String("bcccc");


And to recap Mockito a bit: Mockito is used to mock objects and control the behavior of the objects in Unit Testing, for example, suppose we have a piece of code which has the following dependency, and we want to unit testing A, without Mockito, we will have to create the whole dependency graph which is a big pain.

However, if we use Mockito, then we can mock the use of B and C within A and thus decouple the dependency graph into the following simpler one.

Written on April 9, 2015