1

I have this:

class MyClass {
    private String foo;
    public getFoo() { return foo; }
    public setFoo(String foo) { this.foo = foo; }
}

Now, I want to mock it.

MyClass m = Mockito.mock(MyClass.class);
when(m.getFoo()).thenCallRealMethod();
when(m.setFoo(Mockito.anyString())).thenCallRealMethod(); 

But this gives me this compile error:

'void' type not allowed here

Using thenCallRealMethod() seems to work for methods with no arguments, but I cannot get it to work with arguments. What am I doing wrong?

klutt
  • 30,332
  • 17
  • 55
  • 95

2 Answers2

2

Since void methods cannot return anything, including a mockito matcher, you need to use a different syntax for those:

doCallRealMethod().when(m).setFoo(Mockito.anyString())
Felk
  • 7,720
  • 2
  • 35
  • 65
1

You could also spy on the object, this will only mock the defined methods

For further information Use Mockito to mock some methods but not others

Iwanho22
  • 21
  • 5