gpt4 book ai didi

java - 使用传出 HTTP 请求测试 void 方法

转载 作者:行者123 更新时间:2023-11-28 21:24:25 24 4
gpt4 key购买 nike

我在 SO 上查找了一些较旧的问题,你们中的大多数人都说,不要测试 void 方法。

我有一个向服务器发送 HTTP 请求的方法,我想我仍然应该测试它,即使该方法无效?如果没有,请告诉我原因,因为例如 dzone 的许多教程都提到您应该测试休息请求。

如果我应该测试它,请帮助我回答什么我必须测试以及如何我这样做,因为 void 不返回任何东西。如果你看到另一个不行,请也告诉我,我想尽可能地改进。

方法如下:

private void buy(double price) {
final String timestamp = String.valueOf(System.currentTimeMillis());
final String amount = String.valueOf(observer.requestedAmount);
final String ressouce = GetValuesTypes.getRessource("user").get(observer.getRelatedUser);

String queryArgs = "wwww.doSomething.com/" + ressouce;
String hmac512 = HMAC512.hmac512Digest(queryArgs);

CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost post = new HttpPost(GetValuesTypes.getURL());
post.addHeader("Key", GetValuesTypes.getKey());
post.addHeader("Sign", hmac512);
try {
post.setEntity(new ByteArrayEntity(queryArgs.getBytes("UTF-8")));
} catch (UnsupportedEncodingException e) {
System.out.println("Exception in run");
}
List<NameValuePair> params = new ArrayList<>();

params.add(new BasicNameValuePair("command", "order"));
params.add(new BasicNameValuePair("ressource", ressource));
params.add(new BasicNameValuePair("rate", String.valueOf(rate)));
params.add(new BasicNameValuePair("amount", amount));
params.add(new BasicNameValuePair("timestamp", timestamp));
try {
post.setEntity(new UrlEncodedFormEntity(params));
CloseableHttpResponse response = httpClient.execute(post);
HttpEntity entity = response.getEntity();
Scanner in = new Scanner(entity.getContent());
String orderNumber = "";
while (in.hasNext()) {
orderNumber = in.nextLine();
}
String[] findOrderNumber = orderNumber.split(".");
long lastOrderNumber = -1;
try {
lastOrderNumber = Long.valueOf(findOrderNumber[3]);
} catch (NumberFormatException exception) {
System.out.println("NumberFormatException");
} finally {
if (lastOrderNumber != -1) {
observer.setOrderNumber(lastOrderNumber);
}
}
in.close();
EntityUtils.consume(entity);
httpClient.close();
} catch (IOException e) {
System.out.println("Exception occured during process");
}
}

最佳答案

你不应该直接测试 private 方法。相关主题:

但是,如果您正在测试并且需要模拟它,您可以使用 PowerMock - 允许您对通常被视为不可测试的代码进行单元测试的 Java 框架。代码示例:Mockito Mock Private Method Example with PowerMock

关于java - 使用传出 HTTP 请求测试 void 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44199117/

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