gpt4 book ai didi

java - 单元测试 Web API 消费者模块

转载 作者:太空宇宙 更新时间:2023-11-04 08:02:38 25 4
gpt4 key购买 nike

我的代码是 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 的 Controller ,只是消费者。据说在单元测试中,不应该发出http请求。在这种情况下,如何对 populateNewsArray() 函数进行单元测试,以查看对象映射是否正确(没有任何异常)并返回有效的 HashMap ?

最佳答案

您应该将 getNews() 提取到一个单独的接口(interface)中,例如NewsReader(虽然Reader这个词在JDK中有特定的含义,但我喜欢这个名字...)

public interface NewsReader {
InputStream getNews(String request, boolean bulk) throws Exception
}

然后根据您的代码使用 HttpURLConnection 实现该接口(interface),并更新您的代码以允许注入(inject)该特定接口(interface)。然后,如果您需要测试代码如何处理 InputStream,您可以创建 NewsReader 的模拟,它返回具有众所周知内容的 InputStream

请记住以高内聚为目标:您的类不应该是 HTTP 客户端流解析器。

关于java - 单元测试 Web API 消费者模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12597925/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com