vendredi 26 mai 2017

Test a void method with an outgoing HTTP request

I looked up some older questions here at SO and most of you say, don't test a void method.

I have a method which sends a HTTP Request to a Server and I think I still should test that even if the method is void? If not, please tell me why because many tutorials at dzone for example mention that you should test rest requests.

If I should test it, please help me to answer what I have to test and how I do that since void doesn't return anything. If you see another no go here please also tell me, I want to improve as much as I can.

Here is the Method:

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");
    }
}

Aucun commentaire:

Enregistrer un commentaire