https://kotlinlang.org logo
#mockk
Title
# mockk
r

Ravin Jain

10/14/2021, 7:00 AM
I am trying to mock the
Copy code
any<File>().outputStream()
I am trying this
Copy code
val mockOs = mockk<FileOutputStream>()
mockkStatic("kotlin.io.FilesKt__FileReadWriteKt")
mockkStatic(Files::class)
val resultFile = mockk<File>()
every { resultFile.path } answers {"somepath"}
every { any<File>().outputStream() } returns mockOs
But always gets this error
Copy code
(No such file or directory)
java.io.FileNotFoundException:  (No such file or directory)
	at java.base/java.io.FileOutputStream.open0(Native Method)
	at java.base/java.io.FileOutputStream.open(FileOutputStream.java:298)
	at java.base/java.io.FileOutputStream.<init>(FileOutputStream.java:237)
	at java.base/java.io.FileOutputStream.<init>(FileOutputStream.java:187)
Any idea ?
m

Mattia Tommasone

10/14/2021, 7:56 AM
yes 🙂 i think what you should be doing is
Copy code
every { resultFile.outputStream() } returns mockOs
You cannot use
any<File>()
that way: any() is to match arguments, not to describe mocks
👍 1
r

Ravin Jain

10/14/2021, 4:07 PM
Tried that getting the same error
e

ephemient

10/14/2021, 7:32 PM
1. you can avoid the string reference to the file facade class with
mockkStatic(File::outputStream)
2. in this case,
any<File>().outputStream()
is correct because the
File
is the receiver of an extension function, which makes it just like a normal argument in every way except syntax 3. I'm pretty sure the problem here is that
FileOutputStream
is from the system classloader and cannot be mocked
if at all possible, you'd be better off switching to java.nio.file and using a virtual filesystem - then you don't even have to worry about mocking
1
m

Matteo Mirk

10/15/2021, 10:27 AM
or you can use this https://github.com/google/jimfs or similar libraries for testing purposes
e

ephemient

10/15/2021, 11:32 AM
yes, that's basically my suggestion: jimfs is a virtual java.nio.file filesystem
it's not the only one, there's also http://commons.apache.org/proper/commons-vfs/ but I've never used it
m

Matteo Mirk

10/15/2021, 11:34 AM
Oh ok thanks for clarifying. Wasn’t aware of this detail, I just suggested the lib because I used it once in a project and was very useful
r

Ravin Jain

10/26/2021, 9:30 PM
I was able to resolve this by using TemporaryFolder from junit
m

Matteo Mirk

10/27/2021, 8:56 AM
nice, TemporaryFolder is good, but consider that it interacts with your filesystem. If you use one of the libs cited above, you’ll get the same result but all in-memory
e

ephemient

10/27/2021, 8:59 AM
I wouldn't consider TemporaryFolder for a unit test due to its interaction with the real filesystem, but it can be useful
210 Views