Search code examples
jmockit

How to use JMockit MockUp for default interface method


Trying to apply a MockUp on a Java 8 default interface method, and JMockit tells me that method cannot be found. This has been tried with JMockit 1.15, 1.19, and 1.25. Here's a very simple use case:

@RunWith(JMockit.class)
public class TestTest {

    public interface MyInterface {
        default void foo(int f) {
            bar(String.valueOf(f));
        }

        void bar(String s);
    }

    public class MyClass implements MyInterface {
        public void bar(String s) {
            System.out.println(s);
        }
    }

    @Test
    public void testtest() throws Exception {
        new MockUp<MyClass>() {
            @Mock
            void foo(int i) {
                System.out.println("MOCKMOCK " + (i*2));
            }

            @Mock
            void bar(String s) {
                System.out.println("MOCK " + s);
            }
        };

        MyClass baz = new MyClass();

        baz.foo(5);
        baz.bar("Hello world");
    }

}

This gets me the error

java.lang.IllegalArgumentException: Matching real methods not found for the following mocks:
com.example.dcsohl.TestTest$1#foo(int)
    at com.example.dcsohl.TestTest$1.<init>(TestTest.java:29)
    at com.example.dcsohl.TestTest.testtest(TestTest.java:29)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    ...

How can we @Mock this method?


Solution

  • Use @Mocked instead of a MockUp, it supports default methods.