使用 jmockit 的 Expectations 在测试中模拟 class 的私有方法时得到 IllegalStateException

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

我正在使用 jmockit-1.26 模拟正在测试的 class 的私有方法。 我已经成功地通过 MockUp 模拟了这些方法。但它比 Expectations 更复杂。我尝试使用 Expectations 来做到这一点。但是我在 运行 测试 class.

时得到了 IllegalStateException

正在测试的class:

public class ClassUnderTest1
{

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


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

测试 class 使用期望:

@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());
    }

}

运行 测试用例时的异常:

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.<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)

我不知道,正在寻求帮助。

答案如下: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.

根据此更改,自 v1.23 起无法通过 Expectations API 模拟私有方法。 :(