我的代码是 API 的使用者 (www.abc.com/public/news/apple.json)。我得到一个 json 数组作为回报,然后我解析并填充到我自己的数据结构中。负责执行此操作的代码是:
public Map<String,List<NewsItem>> populateNewsArray() throws Exception
{
url = domain + newsApiStr;
InputStream stream = getNews(url, true);
//jackson library object mapper
ObjectMapper mapper = new ObjectMapper();
//NewsApiObject class implements the structure of the json array returned.
List<NewsApiObject> mappedData = mapper.readValue(stream, NewsApiObject.class));
//populate the properties in a HashMap.
//return HashMap
}
public InputStream getNews(String request, boolean bulk) throws Exception
{
URL url = new URL(request);
connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setInstanceFollowRedirects(false);
connection.setRequestMethod("GET");
connection.setRequestProperty("Content-Type", "text/plain");
connection.setRequestProperty("charset", "utf-8");
connection.connect();
return connection.getInputStream();
}
如您所见,我不是 api 的控制器,只是消费者。据说在单元测试中,不应该发出http请求。在这种情况下,如何对 populateNewsArray() 函数进行单元测试以查看对象映射是否正确(没有任何异常)并返回有效的哈希图?