私のコードは 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() 関数を単体テストして、オブジェクト マッピングが (例外なく) 正しく、有効なハッシュマップが返されたかどうかを確認するにはどうすればよいでしょうか?