gpt4 book ai didi

java - 如何基于 HTTP 连接测试代码

转载 作者:行者123 更新时间:2023-11-30 06:39:03 25 4
gpt4 key购买 nike

我正在开发一个可以解析从 HTTP 端点检索的 XML 的系统。当我考虑如何测试我的代码时,我不希望我的单元测试实际上向实时站点发出 HTTP 请求。似乎是个好习惯。

所以我把读取端点内容的代码封装在这个类中,这样我就可以用 Mockito 模拟它。但是现在,我如何为这个类编写单元测试呢?我刚刚把这个问题推到了一边,现在我还得应付它。

我可以再次包装 URL 对象,但我只是在推卸责任。

我正在尝试遵循“干净代码”中的TDD 3定律

  • 第一定律:在编写失败的单元测试之前,您不得编写生产代码。

  • 第二定律:您编写的单元测试不得超过足以失败的程度。

  • 第三定律:您编写的生产代码不得超过足以通过当前失败测试的代码。

完成这门课我已经违反了第一定律,但我不明白如何通过单元测试来解决这个问题。有什么建议吗?

/**
* Fetches the content from an HTTP Resource
*/
public class HttpFetcher {

/**
* Gets the contents of an HTTP Endpoint using Basic Auth, similar to how Postman (chrome extenstion) does.
*
* @param username Username to authenticate with
* @param password Password to authenticate with
* @param url URL of the endpoint to read.
* @return Contents read from the endpoint as a String.
* @throws HttpException if any errors are encountered.
*/
public String get(String username, String password, String url) {
URLConnection connection;

// Establish Connection
try {
connection = new URL(url).openConnection();
String credentials = encodeCredentials(username, password);
connection.setRequestProperty("Authorization", "Basic " + credentials);
} catch (MalformedURLException e) {
throw new HttpException(String.format("'%s' is not a valid URL.", e));
} catch (IOException e) {
throw new HttpException(String.format("Failed to connect to url: '%s'", url), e);
}

// Read the response
try {
String contents = readInputStream(connection.getInputStream());
return contents;
} catch (IOException e) {
throw new HttpException(String.format("Failed to read from the url: '%s' ", url), e);
}
}

private String encodeCredentials(String username, String password) {
String credentials = String.format("%s:%s", username, password);
String encodedCredentials = new String(Base64.encodeBase64(credentials.getBytes()));
return encodedCredentials;
}

private String readInputStream(InputStream is) throws IOException {
try (BufferedReader reader = new BufferedReader(new InputStreamReader(is))) {
return reader.lines().collect(Collectors.joining("\n"));
}
}
}

最佳答案

您可以将连接的创建移至某个外部类,然后模拟该类:

class HttpFetcher {
private final ConnectionCreator connectionCreator;

...

public HttpFetcher(ConnectionCreator connectionCreator) { this.connectionCreator = connectionCreator; }
public String get(...) {
...
try {
connection = connectionCreator.createConnectionForUrl(url);
...

这也是对单一职责原则的一个小改进:一个类用于从连接获取数据,一个类用于实际创建连接。

关于java - 如何基于 HTTP 连接测试代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44708101/

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