Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mockito- calling real method

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?

like image 431
Java Spring Coder Avatar asked Jun 20 '13 16:06

Java Spring Coder


People also ask

Does Mockito call real method?

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().

Can we mock a method?

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.

What is the difference between @mock and @MockBean?

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 ...

How do you mock a final method?

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.


1 Answers

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(); 
like image 199
ndrone Avatar answered Oct 14 '22 09:10

ndrone