I am trying to mock the ```any<File>().outpu...
# mockk
r
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
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
Tried that getting the same error
e
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
or you can use this https://github.com/google/jimfs or similar libraries for testing purposes
e
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
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
I was able to resolve this by using TemporaryFolder from junit
m
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
I wouldn't consider TemporaryFolder for a unit test due to its interaction with the real filesystem, but it can be useful
251 Views