Mockito can't mock class with file input stream

Viewed 329

I am attempting to mock a static method on a class using PowerMock and Mockito, but something about having a file InputStream in that class (in a seemingly unrelated method) is throwing a MockitoException.

I would like to mock the return value of CustomProperties.getProperty(), but when I run my test I'm getting a MockitoException saying it cannot mock the class. I have tried to suppress the static initializer and loadProperties method in my test, and log statements show they are being suppressed. The problem is around the try/catch within the loadProperties method. As soon as I comment out the try/catch with the file input stream, the test passes. Can someone explain this mystery?

Here's the class (edited for brevity):

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();
    }
}

Here's my test:

@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"));
    }
}

Here's the exception stack trace (edited for brevity):

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
    ...

And finally, the version of the relevant dependencies:

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
0 Answers
Related