Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 666
tamird14 Avatar asked Oct 14 '15 12:10

tamird14


People also ask

How does Mockito when thenReturn work?

Later, when we're calling when() , Mockito pulls that ongoing stubbing object and returns it as the result of when() . Then we call thenReturn(“1”) on the returned ongoing stubbing object.

What is the difference between doReturn and thenReturn?

Following are the differences between thenReturn and doReturn : * Type safety : doReturn takes Object parameter, unlike thenReturn . Hence there is no type check in doReturn at compile time. In the case of thenReturn , whenever the type mismatches during runtime, the WrongTypeOfReturnValue exception is raised.

How to mock an interface using Mockito?

The Mockito. mock() method allows us to create a mock object of a class or an interface. We can then use the mock to stub return values for its methods and verify if they were called. We don't need to do anything else to this method before we can use it.

What is Mockito stubbing?

A stub is a fake class that comes with preprogrammed return values. It's injected into the class under test to give you absolute control over what's being tested as input. A typical stub is a database connection that allows you to mimic any scenario without having a real database.


1 Answers

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());
like image 192
Sajan Chandran Avatar answered Sep 28 '22 06:09

Sajan Chandran