6

I need help with the unit test case. I want to mock static method write(Path path, byte[] bytes, OpenOption... options) of java.nio.file.Files class.

I tried eg. in that way:

PowerMockito.doReturn(path).when(Files.class, "write", path, someString.getBytes());

In this case the method is not found.

PowerMockito.doReturn(path).when(Files.class, PowerMockito.method(Files.class, "write", Path.class, byte[]
            .class, OpenOption.class));

This time i have UnfinishedStubbingException.

How can I do it correct?

  • 3
    Why not use a fake `FileSystem` the way you're supposed to? Mocking static methods is already a major smell. – Louis Wasserman Mar 30 '16 at 18:18
  • 1
    Seconding Louis--Java's built-in filesystem tools are not good for mocking, even when using tools like PowerMockito to exceed Mockito's limitations. – Jeff Bowman Mar 30 '16 at 21:31
  • Thanks Louis. I used the way you proposed and I used [this](https://github.com/marschall/memoryfilesystem) library to create in-memory FileSystem. Its better solution for me. – Mariusz Mączkowski Mar 31 '16 at 14:13

1 Answers1

0

I only had one service that writes to the file system, so I decided to use Mockito only:

import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyString;
import static org.mockito.Matchers.anyVararg;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import org.springframework.test.util.ReflectionTestUtils;

Path mockPath = mock(Path.class);
FileSystem mockFileSystem = mock(FileSystem.class);
FileSystemProvider mockFileSystemProvider = mock(FileSystemProvider.class);
OutputStream mockOutputStream = mock(OutputStream.class);
when(mockPath.getFileSystem()).thenReturn(mockFileSystem);
when(mockFileSystem.provider()).thenReturn(mockFileSystemProvider);
when(mockFileSystemProvider.newOutputStream(any(Path.class), anyVararg())).thenReturn(mockOutputStream);
when(mockFileSystem.getPath(anyString(), anyVararg())).thenReturn(mockPath);

// using Spring helper, but could use Java reflection
ReflectionTestUtils.setField(serviceToTest, "fileSystem", mockFileSystem);

Just make sure your service executes the following calls:

Path path = fileSystem.getPath("a", "b", "c");
Files.write(path, bytes);
Jeff E
  • 658
  • 1
  • 8
  • 19