JMockit嘲笑在初始化期间抛出异常的类

时间:2016-06-16 12:39:23

标签: java mocking jmockit

我一直试图创建一个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");
        }
    }
}

现在我可以设置一个Expectation来在调用ADFSecurityUtil.getIdentityManagementProviderClassName();时返回一些内容,但是当我尝试加载这个类时我会预见到更多问题。

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

1 个答案:

答案 0 :(得分:1)

好的,所以我设法找到了解决方案!这就是我做的事情

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

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

    unitUnderTest.methodUnderTest();
}