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
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.
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.
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.
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.
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());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With