![](/img/trans.png)
[英]Java8 FileSystems.getDefault throw UnsupportedCharsetException
[英]How can I stub FileSystems.getDefault() method using mockito?
這是問題陳述。 我想確認(在我的 Test 方法中)在我的目標方法中調用了fileSystem.newWatchService()
。 我在我的目標方法中獲得了默認的FileSystem
實例(使用FileSystems.getDefault()
)。 任何人都知道我如何存根FileSystems.getDefault()
以便我可以返回我的 Mock FileSystem 實例?
這是我的測試方法。
@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();
}
}
而不是模擬靜態方法——這通常是設計糟糕的代碼的症狀——而是通過FMS
構造函數傳入FileSystem
。 這是依賴注入點的一部分。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.