Java Spring Coder
Java Spring Coder

Reputation: 1027

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?

Upvotes: 37

Views: 80567

Answers (2)

ndrone
ndrone

Reputation: 3572

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

Upvotes: 45

Java Spring Coder
Java Spring Coder

Reputation: 1027

was missing call to : cMock.m2();

Upvotes: 7

Related Questions