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

Mockito has

when(fixture.foo(specified)).thenReturn(result)

So if the following is called

fixture.foo(actual)

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 fixture.foo in order to get the result. That is, whether return the specified result is determined whether the actual parameter passed to fixture.foo(actual) 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

specified.equal(actual)

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.

package net.tech_wonderland.app.mokito_test;

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.*;

@RunWith(MockitoJUnitRunner.class)
public class AppTest
{
	@Mock
	Rabbit fixture;

	@Test
	public void shouldTestEat() {
		String goodCase = new String("bcccc");
		String goodCase2 = new String("bcccc");
		when(fixture.eat(goodCase)).thenReturn("ccc");

		assertTrue(fixture.eat(goodCase).equals("ccc"));
		assertTrue(fixture.eat(goodCase2).equals("ccc"));
	}
}

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