Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mock java.io.File with an in-memory FileSystem. Maybe JimFs

I'm using a third party library that works with java.io.File instances. I'd like to use this library in my unit tests but I don't want it to create files on disk.

My first idea was to use JimFs to mock the file system but it does not support java.io.File.

My second idea was to mock File with some mocking framework and delegate calls to JimFs but don't know if that will work.

Is there some solution out there to use virtual java.io.File?

like image 840
metrimer Avatar asked Mar 06 '15 10:03

metrimer


People also ask

What is Jimfs?

Jimfs is an in-memory file system that implements the Java NIO API and supports almost every feature of it. This is particularly useful, as it means we can emulate a virtual in-memory filesystem and interact with it using our existing java.

How do you move mock files?

It is actually moving the file under src/test/resources. you can use PowerMock for mocking static methods or you may extract Files. move() to some method object and mock it with Mockito library. I would choose second one.


1 Answers

You could use a JUnit TemporaryFolder rule to easily create temporary files that are deleted after the test method is complete.

like image 105
Duncan Jones Avatar answered Nov 02 '22 19:11

Duncan Jones