Java – Mocking non-public static methods in abstract classes with JMockit

javajmockitmockingunit testing

I have the following class:

public abstract class AbstractParent {
    static String method() {
        return "OriginalOutput";
    }
}

I want to mock this method. I decide to use JMockit. So I create a mock class:

public class MockParent {
    static String method() {
        return "MOCK";
    }
}

And my test code looks like this:

public class RealParentTest {

    @Before
    public void setUp() throws Exception {
        Mockit.redefineMethods( AbstractParent.class, MockParent.class );
    }


    @Test
    public void testMethod() {
        assertEquals(MockParent.method(),AbstractParent.method());
    }

}

Unfortunately this test says that AbstractParent returns "OriginalOutput" instead of "MOCK". Any ideas why? Am I doing something wrong? I've tried declaring my mock class as abstract as well, to no avail.

Edit Note that making the method public causes the test to run without a problem… this is weird because with JMockit you are supposed to be able to mock methods of any scope.

Answer Only the mock method needs to be public, you can leave the original method as is.

Best Answer

Found the solution: you simply need to make the mock's method public (the original method can stay in its original visibility).

I don't know why this works while the original way doesn't (someone who does is more than welcome to chime in), but all you need to do is simply change the mock class in the example above to:

public class MockParent {
    public static String method() {
        return "MOCK";
    }
}