WesternGun
WesternGun

Reputation: 12748

Mockito.when calling with real object return null, must use any()

When I unit test with a mock @Service, I notice that in the Mockito.when() statement, when I save the real object, I get null as return; and I have to use any().

So, instead of using:

@Mock
private BinInfoService service;
...  
@Test
public void testSave() {
    SomeBean bean = new SomeBean();
    Mockito.when(service.saveBinInfo(bean).thenReturn(bean);
}

I have to use:

Mockito.when(service.saveBinInfo(Mockito.any(SomeBean.class))).thenReturn(bean);

The first form returns null. While the second form returns the saved entity.

Why?

EDIT:

Sorry actually I am not instantiate the object like above. I used two other ways. See my answer.

Upvotes: 0

Views: 2176

Answers (2)

WesternGun
WesternGun

Reputation: 12748

After all I just found why. The description of the question was misleading so I have to note it.

There are two cases.

  1. In one method, I save the entity with mocked Rest calls, passing the entity as serialized json in as argument. I guess that when doing it the context will create new object every time and the memory address is distinct.

  2. In another method, I save an entity declared as a private field, and the instantiation code method is annotated with @Before. So before every test it will be created once, therefore the memory address is distinct, again.

Upvotes: 1

JPinzon01
JPinzon01

Reputation: 116

From https://static.javadoc.io/org.mockito/mockito-core/2.22.0/org/mockito/Mockito.html#argument_matchers

"Mockito verifies argument values in natural java style: by using an equals() method"

Probable your bean doesn't have an equals method implemented, so it returns null because a new bean is not equals to another by the default implementation. The matcher, on the other hand, allows any bean of that class, so it always returns the value.

Upvotes: 1

Related Questions