Testing Spring HTTP Caching

986 views Asked by At

I have springboot application that enable http caching. I'm using webRequest.checkModifiedSince as describe in here. When running my application in browser I get correct result, 200 status code on first hit and 304 on next hit. But when I run maven test to my application it seems that webRequest.checkModifiedSince always return false.

Here is my testcase :

@Test
public void checkCache() throws Exception {
    MvcResult res = this.mockMvc.perform(get("/resource/to/cache.jpg"))
                        .andExpect(status().isOk())
                        .andReturn();

    String date = res.getResponse().getHeader("Last-Modified");
    HttpHeaders headers = new HttpHeaders();
    headers.setIfModifiedSince(Long.parseLong(date));
    headers.setCacheControl("max-age=0");

    this.mockMvc.perform(get("same/resource/as/above.jpg")
                .headers(headers))
                .andExpect(status().isNotModified());
}

Did I do something wrong here?

2

There are 2 answers

0
Brian Clozel On BEST ANSWER

When sending conditional HTTP requests, you should usually only send If-Modified-Since (using the Last-Modified value) and If-None-Match (using the Etag value).

In this example, you're also sending a max-age=0 directive which means "don't give me anything that's older than 0 seconds", indeed asking the server to send the response anyway (see RFC doc about max-age). This is typically the kind of directive you'd see in browser requests when doing a "hard refresh".

Remove that directive from the request and the server should respond 304 Not Modified.

1
Ralph On

The Last-Modified header is a string like: Wed, 15 Nov 1995 04:58:08 GMT. So I highly doubt that you can parse them to an Long.

I think that your test is failing because an parse exception.

String dateString = res.getResponse().getHeader("Last-Modified");
SimpleDateFormat format = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz");
Date date = format.parse(dateString);

@See: How to parse Date from HTTP Last-Modified header?