Search code examples
javaunit-testingmockito

Use Mockito to mock java.nio.file.Files static methods


I'm trying to understand how you can mock static methods, specifically from the static Files.class.

Basically, whenever this line executes:

 Files.newInputStream(this.getPathObj(), StandardOpenOption.READ);

I want it to just return an object that is an instance of an InputStream.

The is my class with the static method I'm trying to mock.

public class JavaFileInput{

private Path path;

public JavaFileInput(Path path){
    this.path = path;
}

public InputStream getInputStream() throws IOException {
    return Files.newInputStream(this.getPathObj(), StandardOpenOption.READ);
}

public Path getPathObj() {
    return this.path;
}

}

This is some "psuedo-ish" unit test code that obviously doesn't work, but I hope it portrays the idea of what I'm trying to accomplish.

@Mock(name="path")
private Path mockedPath = Mockito.mock(Path.class);

@InjectMocks
private JavaFileInput javaFile_MockedPath;

@Before
public void testSetup(){
  javaFile_MockedPath = new JavaFileInput(mockedPath);
  MockitoAnnotations.initMocks(this);
}

@Test
public void getNewInputStreamTest(){
    //Setup
    Mockito.when(Files.newInputStream(mockedPathObj, StandardOpenOption.Read)).thenReturn(new InputStream());

    //Test
    InputStream outputValue = javaFile_MockedPath.getInputStream();

    //Validate
    assertTrue(outputValue instanceof InputStream);

}

Does this make any sense? Has anyone ever had to do something similar? Any help would be greatly appreciated.

Thanks for your time!


Solution

  • I'm not clear what value your JavaFileInput provides. However, to test static methods you can look at PowerMock.