简体   繁体   中英

Test an outgoing HTTP request in Spring

I feel very sorry to ask that question because I am pretty sure that this was already asked. But by searching here or with google I always land at sites where REST services with incoming requests are tested.

In my case I have a method that sends a request to a server. I want to test if that request is correct. I use java and spring boot. Every time I test that, the request is send to the server. Can I intercept that?

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

I would appreciate your help very much.

This is a typical question that are faced by all the people who are trying to write tests for their code (and this also means that there are many articles on the net about how to do it).

In this particular case, I see two ways:

  • if you want to write a unit test: instead of creating HttpClient, you should make it configurable, to be able to substitute it by mock in the unit tests. You can hold it as a class member or provide as a second argument to buy() method. Later, in a unit test, you need to provide a fake version of HttpClient (mock) that allows you to inspect its arguments to ensure that they're equal to expected.

  • if you want to write an integration test: you need to run a fake service that behaves like a real server but also allows to inspect received requests. In an integration test, you need to configure HttpClient to connect to this fake server and after that check that the server received request from a client.

How to implement this, is up to you and technologies with that you're familiar to.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM