Search code examples
javamockitofilesystemwatcherstubbing

How can I stub FileSystems.getDefault() method using mockito?


Here is the problem statement. I want to confirm (in my Test method) that fileSystem.newWatchService() is invoked within my target method. I am getting the default FileSystem instance (using FileSystems.getDefault()) in my target method. Anyone know how I can stub FileSystems.getDefault() so that I can return my Mock FileSystem instance?

Here is my test method.

@Test
public final void FMS_Creates_A_New_FolderWatcher_From_FileSystem()
{
    try {

        // Arrange
        FileSystem mockFileSystem = mock(FileSystem.class);

        // Your solution will go here!!!
        when(FileSystems.getDefault()).thenReturn(mockFileSystem); // this doesn't work!!
        // Act
        FMS _target = new FMS();
        _target.run();

        // Assert
        verify(mockFileSystem, times(1)).newWatchService();
    } catch (IOException e) {
        // There handled!!
        e.printStackTrace();
    }
}

Addendum: While I was initially facing problem stubbing the FileSystems.getFileSystem() method, the actual issue was more design oriented. By calling default FileSystem, I was expanding my methods scope of behavior.


Solution

  • Instead of mocking a static method -- which is usually a symptom of badly designed code -- pass in the FileSystem through the FMS constructor instead. This is part of the point of dependency injection.