简体   繁体   中英

How to test a HTTP request

I have set up this simple http request, which simply returns a "hello world" response to my IDE terminal. I have been looking into testing and I am not quite sure how i would test what this method is returning.

Currently i have done my own research into JUnit, but again i am not even sure if this would be the correct tool to use for this problem. I only researched this as it is a Java tool.

public static void newRequest() throws IOException {

    URL helloServer = new URL("http://localhost:5050/");

    HttpRequestFactory requestFactory = new NetHttpTransport().createRequestFactory();
    HttpRequest request = requestFactory.buildGetRequest(new GenericUrl(helloServer));

    HttpResponse rawResponse = request.execute();
    String responseString = rawResponse.parseAsString();

    logger.debug(responseString);

}

Any guidance on this would be greatly appreciated. Does the function even need to be tested?

Does the function even need to be tested? Well, that is entirely up to you. Does this function contain code that is critical to your application? If so then yes. If the impact of a bug in this function is minimal then probably not.

Assuming that you want to test this, then:

The method in question is not returning anything void before the function name says this. You will need to look at testing the logic of the function. In this case you need to check that the correct response is received. There are two ways that I can think of to do this:

  1. Modify the code to return the response.

You could change the function to return a String and then return rawResponse.parseAsString(); (which is the same thing you are logging.

Then you can call the function from the test and check the String that is returned.

  1. Get the log message from your logger.

Depending on the logging that you are using, you could get the log message that was written by the function. Assuming log4j then there are some posts on how to do this:

log4j: how to get the last inserted log message?

Personally, I prefer the first option as it is less effort. I would also consider returning the body of the response rather than the raw response.

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