Search code examples
javamockingillegalstateexceptionjmockitprivate-methods

Got IllegalStateException while mocking private method of class under test using Expectations by jmockit


I'm using jmockit-1.26 to mock private methods of class under test. I've succeed to mock these methods by MockUp. But it is more complicated then Expectations. I'm try to use Expectations to do this. But I got IllegalStateException while running the test class.

The class under test:

public class ClassUnderTest1
{

    public String publicMethod1()
    {
        return privateMethod1();
    }


    private String privateMethod1()
    {
        return "The real privateMethod1";
    }
}

The test class using Expectations:

@RunWith(JMockit.class)
public class TestCase1
{
    @Tested
    private ClassUnderTest1 t1;

    @Test
    public void test()
    {
        new Expectations(t1)
        {
            {
                Deencapsulation.invoke(t1, "privateMethod1");
                result = "Mocked privateMethod1";
                times = 1;
            }
        };

//        This MockUp works fine.
//        new MockUp<ClassUnderTest1>(t1)
//        {
//            @Mock
//            private String privateMethod1()
//            {
//                return "Mocked privateMethod1";
//            }
//        };

        System.out.println(t1.publicMethod1());
    }

}

The exception while running the test case:

java.lang.IllegalStateException: Missing invocation to mocked type at this point; please make sure such invocations appear only after the declaration of a suitable mock field or parameter
at jmockit.TestCase1$1.<init>(TestCase1.java:32)  <- This line is result = "Mocked privateMethod1";
at jmockit.TestCase1.test(TestCase1.java:28)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:678)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)

I have no idea and looking for help.


Solution

  • Here's the answer: http://jmockit.org/changes.html#1.23

    Dropped support for the mocking of private methods/constructors when using the Expectations API, to prevent misuse. If still needed, they can be mocked or stubbed out with the application of a MockUp.

    According to this change, It is not possible to mock private methods by Expectations API since v1.23. :(