簡體   English   中英

Java中的URL單元測試

[英]URL unit testing in Java

我正在為一些數據獲取程序編寫測試,該數據獲取程序從一些URL獲取信息並使用JSOUP對其進行解析。

方法之一:

public Map<String, String> getDepartments() {
    Map<String, String> result = new HashMap<>();
    Document doc = null;

    try {
        doc = Jsoup.connect(globalScheduleURL).get();
    } catch (IOException e) {
        e.printStackTrace();
    }

    Elements links = doc.select("a[href]");
...
}

其中globalScheduleURL是一個String ,通常設置為http://universitysite.edu/... 為了進行測試,我制作了所需頁面的模擬副本,並將其保存在./src/test/resources下。 我如何訪問本地文件,所以地址以file:/開頭。

當我嘗試做這樣的事情:

@Before
public void initializeDataFetcher() throws MalformedURLException {
    df = new SSUDataFetcher();

    File file = new File("./src/test/resources/departments.html");
    URL fileURL = file.toURI().toURL();

    System.out.println(fileURL);
    df.setGlobalURL(fileURL.toString());


}

我得到:

file:.../src/test/resources/departments.html java.net.MalformedURLException: Only http & https protocols supported

有什么解決方法可以避免JSoup中的此異常或Java中的某些URL格式? `

我希望將URL提取到自己的類/方法中(因為從URL讀取不是關鍵任務代碼)-有趣的部分是HTML的解析,這可以通過接受HTML的方法輕松完成, String並返回解析的結果,而無需讀取實際的URL,您可以通過為其提供靜態String輕松模擬該方法。

doc = Jsoup.connect(globalScheduleURL).get(); 

無法測試,因為connect()是靜態方法。 要對此進行測試,您需要首先將這一行代碼提取到自己的方法中

Document getDocumentHelper(String globalScheduleURL) throws IOException {
        return Jsoup.connect(globalScheduleURL).get();
}

然后使用Mockito,EasyMock,PowerMock或Spock等模擬框架對這個方法進行存根返回模擬文檔,並在原始測試中使用它。 例如,在Spock中:

Document doc = mock(Document) 
classUnderTest.getDocumentHelper(globalScheduleURL) >> doc

或Mockito:

Document doc = mock(Document.class); 
when(classUnderTest.getDocumentHelper(globalScheduleURL)).thenReturn(doc); 

真正的問題是,在編寫程序時並未考慮到可測試性。 為獲取數據的零件創建一個抽象,以便您可以在測試中注入模擬實現。

暫無
暫無

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

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