Skip to content
Advertisement

How to mock a Files static method with Mockito

I have a method in my utilities:

JavaScript

I want to mock Files so I can test to make sure Files.createDirectories with the expected fields are called or not.

Can I do this with Mockito? Or do I need to actually create the directories and check for their existence in some tmp folder?

Advertisement

Answer

When you write something with tdd and have troubles consider it as signal of bad design. You don’t need to mock static fields or find some tricky lib for do it. Instead of doing this make entity that represent filesystem and place all methods related to file operations to this class. With this refactor your code will be like that:

JavaScript

and test class

JavaScript

In your code outside tests replace mock to implementation.

JavaScript

and you don’t need to touch file system in tests or mock static fields.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement