I have a class which has 2 methods. I want to mock the class and then mock the first method but not the 2nd one.
e.g.
class C { void m1() { ...} boolean m2() { ... return flag;} }
unit test code:
C cMock = Mockito.mock(C.class); Mockito.doNothing().when(cMock).m1(); Mockito.when(cMock.m2()).thenCallRealMethod();
The strange thing is that m2 is not being called.
do I miss anything here?
Mockito allows us to partially mock an object. This means that we can create a mock object and still be able to call a real method on it. To call a real method on a mocked object we use Mockito's thenCallRealMethod().
Mocking is done when you invoke methods of a class that has external communication like database calls or rest calls. Through mocking you can explicitly define the return value of methods without actually executing the steps of the method.
Main difference between @MockBean and @Mock annotation is that @MockBean creates mock and injects it into Application Context, while @Mock annotation only creates it, if you want to inject it, you can do it manually or with @InjectMocks annotation, however injection is being done to the class not whole Application ...
Configure Mockito for Final Methods and Classes Before we can use Mockito for mocking final classes and methods, we have to configure it. Mockito checks the extensions directory for configuration files when it is loaded. This file enables the mocking of final methods and classes.
This is also where Mockito.spy
can be used. it allows you to do partial mocks on real objects.
C cMock = Mockito.spy(new C()); Mockito.doNothing().when(cMock).m1();
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