gpt4 book ai didi

java - 对使用 httpclient 的类进行单元测试

转载 作者:行者123 更新时间:2023-12-01 17:55:46 26 4
gpt4 key购买 nike

我想为这个使用HttpURLConnection的类编写单元测试用例。到目前为止我还没有使用过任何模拟框架,因此很难最终确定该方法。

public class DemoRestClient implements Closeable {

private final String instanceId;
private final String requestId;
private HttpURLConnection conn;

public DemoRestClient(String instance, String reqId, String url) {
this.instanceId = instance;
this.requestId = reqId;

try {
URL urlRequest = new URL(url);
conn = (HttpURLConnection) urlRequest.openConnection();
} catch (IOException iox) {
throw new RuntimeException("Failed to connect", iox);
}
}

public InputStream run() {

try {
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept", "application/json");
conn.setRequestProperty("Accept-Encoding", "gzip");

if (conn.getResponseCode() != 200) {
throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode());
}

return new GZIPInputStream(conn.getInputStream());
} catch (IOException iox) {
throw new RuntimeException("Data fetching failed!", iox);
}
}

@Override
public void close() throws IOException {
if (conn != null) {
conn.disconnect();
}
}
}

如果您经历过这种情况,请遮挡一些光线。谢谢!

最佳答案

您必须在构造时提供 HttpURLConnection 或让 DemoRestClient 委托(delegate)给工厂(或类似工厂)来创建 HttpURLConnection

例如:

public DemoRestClient(String instance, String reqId, HttpURLConnection connection) {
...
this.conn = connection;
}

或者

public DemoRestClient(String instance, String reqId, ConnectionFactory connectionFactory) {
...
this.conn = connectionFactory.create();
}

使用这两种方法中的任何一种,您都将控制 DemoRestService 中使用的实际 HttpURLConnection 实例,然后您可以开始模拟它以支持您所需的测试行为。

例如:

@Test
public void someTest() throws IOException {
HttpURLConnection connection = Mockito.mock(HttpURLConnection.class);
String instance = "...";
String reqId = "...";

DemoRestClient demoRestClient = new DemoRestClient(instance, reqId, connection);

// in case you need to mock a response from the conneciton
Mockito.when(connection.getInputStream()).thenReturn(...);

demoRestClient.run();

// in case you want to verify invocations on the connection
Mockito.verify(connection).setRequestMethod("GET");
}

关于java - 对使用 httpclient 的类进行单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45008661/

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