[英]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.