How to Unit Test Cache Control header using JUnit?

2019-09-11 03:31发布

问题:

I just created a CacheControl to use on the response from REST services, it is a ResponseBuilder which takes a ResponseBuilder as parameter on which i set the no cache options. The code is shown below.

        /**
 * Cacheless method to control the Cache Header in REST responses.
 * @param builder the response builder
 * @return Cache Control Header for REST Responses
 */
private ResponseBuilder setCacheControlHeader(final ResponseBuilder builder) {
    CacheControl control = new CacheControl();
    control.setNoCache(true);
    control.setNoStore(true);
    control.setMaxAge(0);
    control.setPrivate(true);
    control.setMustRevalidate(true);
    control.setNoTransform(true);
    builder.cacheControl(control);
    builder.header("Pragma", "no-cache");
    builder.header("Expires", 0);

    return builder;
}

As I am just working on on the methods I am using PostMan to test the headers which seems to be fine. Now I am trying to create a JUnit test to test if the Response builder passed on to the method is getting assigned the parameters on the method such as "noCache, "noStore" and "expires".

I would need to test it for each of my RestServices which is using this method. Can someone suggest how to test it?

Regards

回答1:

Using RestAssured, it is as simple as:

    given().param("bookId", book.getId())
           .get("/api/books/")
           .then()
           .statusCode(HttpStatus.SC_OK)
           .header("Cache-Control", "no-cache, no-store, max-age=0, must-revalidate");