-1

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.

deepthought
  • 87
  • 11
  • 2
    possible duplicate of [Mocking static methods with Mockito](http://stackoverflow.com/questions/21105403/mocking-static-methods-with-mockito) – durron597 Aug 31 '15 at 16:58
  • 1
    Why, why, _why_ would you do this instead of making the `FMS` constructor accept a `FileSystem` argument? Part of the _point_ of the `FileSystem` API is that you can inject alternate filesystems through the constructor instead of trying to hack around the default behavior. – Louis Wasserman Aug 31 '15 at 17:11
  • @LouisWasserman, I knew I was gonna be reprimanded for shortcuts. Yes, you are right, I should inject the FileSystem. argh!!! – deepthought Aug 31 '15 at 17:41
  • 1
    Mocking static things is essentially always an indication that it shouldn't be static; that you should be injecting it instead. – Louis Wasserman Aug 31 '15 at 17:42
  • @durron597, Thanks. Yes, this would be a suitable solution to stub the static method. But I am leaning towards injecting FS. – deepthought Aug 31 '15 at 17:58
  • @LouisWasserman, do you mind re-posting your original comment as an answer instead of comment so that I may tag it as the solution. Thanks. – deepthought Aug 31 '15 at 18:05

1 Answers1

1

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.

Louis Wasserman
  • 191,574
  • 25
  • 345
  • 413