Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/343.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 莫基托可以';t使用文件输入流模拟类_Java_Unit Testing_Mockito_Powermock - Fatal编程技术网

Java 莫基托可以';t使用文件输入流模拟类

Java 莫基托可以';t使用文件输入流模拟类,java,unit-testing,mockito,powermock,Java,Unit Testing,Mockito,Powermock,我试图使用PowerMock和Mockito在一个类上模拟一个静态方法,但是在该类中有一个文件InputStream(在一个看似不相关的方法中)会引发一个MockitoException 我想模拟CustomProperties.getProperty()的返回值,但是当我运行测试时,我得到一个MockitoException表示它无法模拟该类。在我的测试中,我试图抑制静态初始值设定项和loadProperties方法,日志语句显示它们被抑制。问题在于loadProperties方法中的try/

我试图使用PowerMock和Mockito在一个类上模拟一个静态方法,但是在该类中有一个文件InputStream(在一个看似不相关的方法中)会引发一个
MockitoException

我想模拟
CustomProperties.getProperty()
的返回值,但是当我运行测试时,我得到一个
MockitoException
表示它无法模拟该类。在我的测试中,我试图抑制静态初始值设定项和
loadProperties
方法,日志语句显示它们被抑制。问题在于
loadProperties
方法中的try/catch。只要我用文件输入流注释掉try/catch,测试就通过了。有人能解释这个谜吗

下面是课程(为简洁起见编辑):

这是我的测试:

@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: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

嘿,你能更新你的Java版本以使用JDK1.8吗?或者这不是你的选择?我很乐意,但是的,现在不是。这是一个遗憾,据我所知,JDK1.8解决了一些类似的问题。
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