JMockit 模拟 class 在初始化期间抛出异常

JMockit mocking a class that throws an exception during initialisation

例如,我一直在尝试创建 oracle.adf.share.security.identitymanagement.UserProfile 的模拟

@Test
public void testMyTest(@Mocked final UserProfile userProfile) {
    new Expectations() {
        {
           userProfile.getBusinessEmail();
           result = "me@me.com";
        }
    };

    unitUnderTest.methodUnderTest();
}

然而,我发现当 JMockit 尝试构造模拟时抛出异常

java.lang.ExceptionInInitializerError
  at java.lang.Class.forName0(Native Method)
  at java.lang.Class.forName(Class.java:247)
  at oracle.jdevimpl.junit.runner.junit4.JUnit4Testable.run(JUnit4Testable.java:24)
  at oracle.jdevimpl.junit.runner.TestExecution.run(TestExecution.java:27)
  at oracle.jdevimpl.junit.runner.JUnitTestRunner.main(JUnitTestRunner.java:88)
Caused by: oracle.adf.share.security.ADFSecurityRuntimeException: EXC_FAILED_ID_STORE
  at oracle.adf.share.security.identitymanagement.UserManager.<init>(UserManager.java:111)
  at oracle.adf.share.security.identitymanagement.UserManager.<init>(UserManager.java:83)
  at oracle.adf.share.security.identitymanagement.UserProfile.<clinit>(UserProfile.java:62)

反编译后 UserProfile 我可以看到它有这样的东西

public class UserProfile implements Serializable {
    ...
    private static UserManager _usrMgr = new UserManager();
    ...
}

UserManager 构造函数如下所示

public UserManager() {
    this((String) null);
}

public UserManager(String providerClassName) {
    if (providerClassName != null) {
        ...
    } else { 
        String clzName = ADFSecurityUtil.getIdentityManagementProviderClassName();
        if (clzName != null) {
            IdentityManagement provider = (IdentityManagement) createObject(clzName);
            setIdentityManagementProvider(provider);
        } else {
            throw new ADFSecurityRuntimeException("EXC_FAILED_ID_STORE");
        }
    }
}

现在我可以在调用 ADFSecurityUtil.getIdentityManagementProviderClassName(); 时设置对 return 的期望,但是当它尝试加载此 class.

时我预见到更多问题

解决此问题的最佳方法是什么?

好的,所以我设法找到了解决方案 假货!这是我所做的

@Test
public void testMyTest() {
    new Mockup<UserProfile>() {
        @Mock
        public void $cinit() {
            // do nothing
        }

        @Mock
        public String getBusinessEmail() {
            return "me@me.com";
        }
    };

    unitUnderTest.methodUnderTest();
}