簡體   English   中英

如何使用 mockito 存根 FileSystems.getDefault() 方法?

[英]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();
    }
}

附錄:雖然我最初在處理 FileSystems.getFileSystem() 方法時遇到了問題,但實際問題更多的是面向設計。 通過調用默認文件系統,我擴展了我的方法行為范圍。

而不是模擬靜態方法——這通常是設計糟糕的代碼的症狀——而是通過FMS構造函數傳入FileSystem 這是依賴注入點的一部分。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM