Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to call default implementations of interfaces with Mockito's doCallRealMethod?

Tags:

mockito

Suppose I have the following interface:

public interface ISomething {

    default int doStuff() {
        return 2 * getValue();
    }

    int getValue();
}

When I now mock this interface like this:

@Mock
private ISomething _something;

@Before
public void setup() {
    doCallRealMethod().when(_something).doStuff();
}

and try to test the doStuff() method like the following:

@Test
public void testDoStuff() {
    when(_something.getValue()).thenReturn(42);
    assertThat("doStuff() returns 84", _something.doStuff(), is(84));
}

I expect the test to succeed, but I get:

org.mockito.exceptions.base.MockitoException:
Cannot call real method on java interface. Interface does not have any implementation!
Calling real methods is only possible when mocking concrete classes.

I tried subclassing ISomething with an abstract class like this:

public abstract class Something implements ISomething {
}

and mock this class like above. With this approach, I get the same.

Does Mockito not support calling default implementations?

like image 359
rabejens Avatar asked Nov 25 '14 16:11

rabejens


1 Answers

That's correct. The current version of Mockito doesn't support this. You could raise a feature request here. Do note that it seems to be related to issue 456 which was fixed in release 1.10.0, so please make sure you test this in the latest version first.

like image 135
Dawood ibn Kareem Avatar answered Jan 03 '23 14:01

Dawood ibn Kareem