java - 使用 JMockit 模拟 ResourceLoading

标签 java junit mocking jmockit

我的应用程序使用保存配置设置的单例。这是代码:

private PropertiesSingleton() throws Exception {
    InputStream appstream = this.getClass().getClassLoader()
            .getResourceAsStream("application.properties");
    props = new Properties();
    try {
        props.load(appstream);
    } catch (IOException e) {
        logger.log(Log.FATAL,
                "Cannot find application.properties in classpath.", e);
        throw e;
    }
}

通常我的应用程序在容器内运行。对于我的单元测试,我必须使 application.properties 可供加载。我尝试过这样的:

@Before
public void init() throws Exception {


    final FileInputStream inStream = new FileInputStream("../path/to/config/application.properties");
    new NonStrictExpectations(ClassLoader.class) {
        {
            String.class.getClassLoader().getResourceAsStream("application.properties"); result = inStream;
        }
    };
}

测试不会启动,但会打印此堆栈跟踪:

java.lang.VerifyError
at sun.instrument.InstrumentationImpl.redefineClasses0(Native Method)
at de.lpm.ejb.archiving.ArchiveHandlerBeanTest$2.<init>(ArchiveHandlerBeanTest.java:50)
at de.lpm.ejb.archiving.ArchiveHandlerBeanTest.init(ArchiveHandlerBeanTest.java:50)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.lang.reflect.Method.invoke(Method.java:597)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:46)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)

最佳答案

我相信模拟类加载器根本不可能,因为它首先存在。在类加载器出现之前你不能做任何事情。因此,请尝试模拟调用者,而不是类加载器。

关于java - 使用 JMockit 模拟 ResourceLoading,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17234599/

相关文章:

java - 流音频振幅的有源阵列

java - 为什么 JUnit 5 Suite 注释 @SelectClasses 和 @IncludeClassNamePatterns 无法找到不以 "Tests"或 "Test"结尾的测试?

java - 验证完成后,EasyMock 在 tearDown 方法中验证对 mock 的调用

c# - 如何使用 Moq 模拟 X509Certificate2?

java - 如何在 JMockit、PowerMocks 等任何模拟框架中模拟静态方法?

java - 查找数组中连续的重复整数

java - 在Java中通过套接字接收FFT数据

java - 在 JUnit 中分组测试并指定在 Maven 中运行哪个

c++ - 谷歌模拟 : Is it ok to use global mock objects?

java - 无法使用 RMI 客户端从 DBMS 恢复数据