Mockito-inline throws Stream closed exception on RandomAccesFile

371 Views Asked by At

I have following lines in my testing code

RandomAccessFile mockRAF = mock(RandomAccessFile.class);
when(mockRAF.length()).thenReturn(len);

with dependency like this

testImplementation "org.mockito:mockito-inline:2.8.47"

and getting

Stream Closed
java.io.IOException: Stream Closed
    at java.base/java.io.RandomAccessFile.length(Native Method)
    at com.example.examplepackage.enterprise.app.Installation$RealFileAccessor.readInstallationFile(Installation.java:87)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:566)
    at java.base/java.lang.Thread.run(Thread.java:834)

this error. I have tried several things but unsuccessfully. Removing mockito-inline is not an option, cause there are a lot of tests mocking final classes. Is there any possible solution I can try out to make this thing work ?

1

There are 1 best solutions below

0
On BEST ANSWER

The reason mocking fails is that RandomAccessFile.length() is a native method.

mockito-inline cannot mock native methods. See Mocking final types, enums and final methods:

Some methods cannot be mocked

  • Package-visible methods of java.*
  • native methods

The approaches to solve:

  • if possible, use one of the interfaces RAF implements in method under test
  • wrap RAF with your own class delegating to RAF
  • use real RAF in tests, but point it to a temporary file you create in the test