Mockito无法通过文件输入流模拟类

问题描述 投票:2回答:1

[我正在尝试使用PowerMock和Mockito在类上模拟静态方法,但是在该类中具有文件InputStream的某种方法(在看似无关的方法中,会抛出MockitoException

我想模拟CustomProperties.getProperty()的返回值,但是当我运行测试时,我得到一个MockitoException说它不能模拟该类。我已尝试在测试中禁止使用静态初始化程序和loadProperties方法,并且日志语句显示它们已被禁止。问题出在loadProperties方法中的try / catch周围。一旦我用文件输入流注释掉try / catch,测试就通过了。有人可以解释这个谜吗?

这里是全班(为简洁起见:]

public class CustomProperties {

    private static Properties properties = null;

    // mock this method's return value
    public static String getProperty(String key) {
        return properties.getProperty(key);
    }

    public static synchronized void loadProperties() {
        properties = new Properties();
        String path = System.getProperty("domain.path");

        try (InputStream fileInputStream = Files.newInputStream(Paths.get(path + "/custom.properties"))) {
            // do stuff
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    static {
        loadProperties();
    }
}

这是我的测试:

@RunWith(PowerMockRunner.class)
@SuppressStaticInitializationFor("com.company.util.CustomProperties")
@PrepareForTest(CustomProperties.class)
public class SanityTest {

    @Before
    public void setUp() throws Exception {
        mockStatic(CustomProperties.class);
        when(CustomProperties.getProperty("someKey")).thenReturn("some value");
        suppress(method(CustomProperties.class, "loadProperties"));
    }

    @Test
    public void sanityTest() {
        assertEquals("some value", CustomProperties.getProperty("someKey"));
    }
}

这里是异常堆栈跟踪(为简便起见进行了编辑:]:>

org.mockito.exceptions.base.MockitoException: 
Mockito cannot mock this class: class com.company.util.CustomProperties.

Mockito can only mock non-private & non-final classes.
If you're not sure why you're getting this error, please report to the mailing list.

Java               : 1.7
JVM version        : 1.7.0_10-b18

Underlying exception : java.lang.IllegalArgumentException: Could not create type
    ...
Caused by: java.lang.IllegalArgumentException: Could not create type
    ...
Caused by: java.lang.VerifyError: Inconsistent stackmap frames at branch target 2947 in method com.company.util.CustomProperties.loadProperties()V at offset 2936
    ...

最后是相关依赖项的版本:

org.mockito:mockito-core:2.28.2
org.powermock:powermock-module-junit4:2.0.2
org.powermock:powermock-api-mockito2:2.0.2
net.bytebuddy:byte-buddy:1.10.1

[我正在尝试使用PowerMock和Mockito在类上模拟静态方法,但是有关在该类中使用文件InputStream的某种方法(在看似无关的方法中,会抛出...

java unit-testing mockito powermock
1个回答
0
投票
它进行了一些细微调整:
© www.soinside.com 2019 - 2024. All rights reserved.