Chi*_*int 5 java unit-testing mockito
我试图了解如何模拟静态方法,特别是来自静态 Files.class 的静态方法。
基本上,每当此行执行时:
Files.newInputStream(this.getPathObj(), StandardOpenOption.READ);
Run Code Online (Sandbox Code Playgroud)
我希望它只返回一个作为 InputStream 实例的对象。
这是我的类,其中包含我试图模拟的静态方法。
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;
}
}
Run Code Online (Sandbox Code Playgroud)
这是一些“伪”单元测试代码,显然不起作用,但我希望它描绘了我想要完成的事情的想法。
@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);
}
Run Code Online (Sandbox Code Playgroud)
这有意义吗?有人曾经做过类似的事情吗?任何帮助将不胜感激。
谢谢你的时间!