如何使用 mockito 存根 FileSystems.getDefault() 方法?
How can I stub FileSystems.getDefault() method using mockito?
这里是问题陈述。我想确认(在我的测试方法中) fileSystem.newWatchService()
在我的目标方法中被调用。我在我的目标方法中获得了默认的 FileSystem
实例(使用 FileSystems.getDefault()
)。任何人都知道我如何存根 FileSystems.getDefault()
以便我可以 return 我的模拟文件系统实例?
这是我的测试方法。
@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();
}
}
附录:虽然我最初遇到了存根 FileSystems.getFileSystem() 方法的问题,但实际问题更多是面向设计的。通过调用默认文件系统,我正在扩展我的方法行为范围。
与其模拟静态方法(这通常是代码设计不当的症状),不如通过 FMS
构造函数传入 FileSystem
。这是依赖注入点的一部分。
这里是问题陈述。我想确认(在我的测试方法中) fileSystem.newWatchService()
在我的目标方法中被调用。我在我的目标方法中获得了默认的 FileSystem
实例(使用 FileSystems.getDefault()
)。任何人都知道我如何存根 FileSystems.getDefault()
以便我可以 return 我的模拟文件系统实例?
这是我的测试方法。
@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();
}
}
附录:虽然我最初遇到了存根 FileSystems.getFileSystem() 方法的问题,但实际问题更多是面向设计的。通过调用默认文件系统,我正在扩展我的方法行为范围。
与其模拟静态方法(这通常是代码设计不当的症状),不如通过 FMS
构造函数传入 FileSystem
。这是依赖注入点的一部分。