简体   繁体   中英

Mockito when().thenReturn() doesn't work properly

I have a class A with 2 functions: function a() which returns a random number. function b() which calls a() and return the value returned.

In a test I wrote this:

A test = Mockito.mock(A.class)
Mockito.when(test.a()).thenReturn(35)
assertEquals(35,test.a())
assertEquals(35,test.b())

The test fails at the second assert. Does anyone know why?

To be clear - this is not my real code, but a simple code to explain my problem

Since class A is mocked, all method invocations wont go to the actual object. Thats why your second assert fails (i guess it might have returned 0).

Solution:

You could do something like

when(test.b()).thenCallRealMethod();

else you could spy like

A test = spy(new A());
Mockito.when(test.a()).thenReturn(35);
assertEquals(35,test.a());
assertEquals(35,test.b());

function b() which calls a()

Maybe it does in your actual concrete A , but that is not being used in this case. Only the mock is being used here.

So you need to tell the mock what to do for every method you want to call:

Mockito.when(test.b()).thenReturn(35);

Because you have only a mock when you call it with test.a().

You have to add Mockito.when(test.b()).thenReturn(35) . then your code works fine

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM