Mocking File is a Pain in the@$$

so you have a program that needs to interact with the filesystem, but how do you mock it?

nio Files from JDK 7 is very handy, however due to the handy method being static, you cannot easily mock it (Except with PowerMock, but we will skip that for now).

so for places where I had to do
File myFile = new File(“…”)

I build a FileFactory to redirect the call
FileFactory fileFactory = new FileFactory() (which is injected to my component)
File myFile = fileFactory.getFile(“…”);

then I can mock my fileFactory
FileFactory mockFileFactory = mock(FileFactory.class);
File mockFile = mock(File.class);


Please let me know if you find a better way to mock the File, preferrably without too many wrappers, or how we could keep using static nio Files and not use PowerMock.

What’s also hard to test? Asynchronous method…..
I will write another post about it.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s