Mockito when (). ThenReturn () is not working properly

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

In the 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 in the second statement. Does anyone know why?

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

+7
java unit-testing mockito mocking
source share
3 answers

Since class A ridiculed, all method calls usually do not go to the actual object. This is why your second statement fails (I think it could return 0).

Decision:

You can do something like

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

otherwise you could spy like

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

function b () that calls a ()

It may happen in your particular concrete A , but it is not used in this case. Only the layout is used here.

So, you need to tell the layout what to do for each method you want to call:

 Mockito.when(test.b()).thenReturn(35); 
+3
source share

Because you only have a layout when you call it using test.a ().

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

+3
source share

All Articles