我的代码是API的使用者(www.abc.com/public/news/apple.json)。我得到一个json数组作为回报,然后我解析并填充到自己的数据结构中。负责这样做的代码是:单元测试Web API消费模块
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()函数以查看对象映射是否正确(没有任何例外)并返回有效的散列表?
btw david,如果我确实为新闻阅读创建了一个接口,我仍然可以如何测试populateNewArray()函数?是否需要彻底更改该功能并删除getNews调用,以便它可以进行单元测试? – samach
@Salmanmahmood'populateNewArray'调用'NewsReader.getNews'。你可以注入一个模拟,它返回一个(例如)包含已知JSON的'ByteArrayInputStream'。 –
我将如何确保模拟对象在测试时被调用,而不是真正的实现(网络调用)? – samach