gpt4 book ai didi

java - Junit:如何模拟 HttpUrlConnection

转载 作者:行者123 更新时间:2023-11-29 03:42:57 25 4
gpt4 key购买 nike

如何将 HttpURLConnection 模拟到示例代码中的 getContent() 方法,以及如何从模拟 url 获取响应

public class WebClient {
public String getContent(URL url) {
StringBuffer content = new StringBuffer();
try {

HttpURLConnection connection = createHttpURLConnection(url);
connection.setDoInput(true);
InputStream is = connection.getInputStream();
int count;
while (-1 != (count = is.read())) {
content.append(new String(Character.toChars(count)));
}
} catch (IOException e) {
return null;
}
return content.toString();
}
protected HttpURLConnection createHttpURLConnection(URL url) throws IOException{
return (HttpURLConnection)url.openConnection();

}
}

谢谢

最佳答案

您的 Webclient 设计得有点不适合测试。您应该避免隐藏的依赖项(基本上是大多数 new 操作)。要成为可模拟的,这些依赖项应该(最好)在其构造函数中提供给被测对象,或者被测对象应将它们保存在一个字段中,以便它们可以被注入(inject)。

或者你可以扩展你的网络客户端

new Webclient() {
@Override
HttpURLConnection createHttpURLConnection(URL url) throws IOException{
return getMockOfURLConnection();
}

其中 getMockOfURLConnection 从 Mockito 等模拟框架返回 HttpURLConnection 的模拟。然后你教那个模拟返回你想要的东西并使用 verify 来检查它是否被正确调用。

关于java - Junit:如何模拟 HttpUrlConnection,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12294987/

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