简体   繁体   English

Java中的URL单元测试

[英]URL unit testing in Java

I'm writing tests for some data fetcher, which gets information from some URL and parses it with JSOUP. 我正在为一些数据获取程序编写测试,该数据获取程序从一些URL获取信息并使用JSOUP对其进行解析。

One of the methods: 方法之一:

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]");
...
}

where globalScheduleURL is a String , usually formatted as http://universitysite.edu/... . 其中globalScheduleURL是一个String ,通常设置为http://universitysite.edu/... For testing purposes I made a mock copy of needed pages and saved it under ./src/test/resources . 为了进行测试,我制作了所需页面的模拟副本,并将其保存在./src/test/resources下。 How can I access to local files, so the address starts with file:/ ? 我如何访问本地文件,所以地址以file:/开头。

When I tried to do something like this: 当我尝试做这样的事情:

@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());


}

I get: 我得到:

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

Is there any workaround to avoid this exception in JSoup or some URL formatting in Java? 有什么解决方法可以避免JSoup中的此异常或Java中的某些URL格式? ` `

我希望将URL提取到自己的类/方法中(因为从URL读取不是关键任务代码)-有趣的部分是HTML的解析,这可以通过接受HTML的方法轻松完成, String并返回解析的结果,而无需读取实际的URL,您可以通过为其提供静态String轻松模拟该方法。

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

is not testable because connect() is a static method. 无法测试,因为connect()是静态方法。 To test this, you would need to first extract this line of code into it's own method 要对此进行测试,您需要首先将这一行代码提取到自己的方法中

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

and then stub this method out to return a mock Document, using a mocking framework like Mockito, EasyMock, PowerMock, or Spock and use it in your original test. 然后使用Mockito,EasyMock,PowerMock或Spock等模拟框架对这个方法进行存根返回模拟文档,并在原始测试中使用它。 For example, in Spock: 例如,在Spock中:

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

Or Mockito: 或Mockito:

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

The real problem is that the program has not been written with testability in mind. 真正的问题是,在编写程序时并未考虑到可测试性。 Create an abstraction for the part that obtains the data, so that you can inject a mock implementation in the test. 为获取数据的零件创建一个抽象,以便您可以在测试中注入模拟实现。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM