35

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?

4

2 回答 2

43

这也是Mockito.spy可以使用的地方。它允许您对真实对象进行部分模拟。

C cMock = Mockito.spy(new C());
Mockito.doNothing().when(cMock).m1();
于 2014-08-23T14:36:36.147 回答
6

缺少对:cMock.m2() 的调用;

于 2013-06-20T16:38:18.820 回答