Edgar Hernandez
Edgar Hernandez

Reputation: 425

How to validate using MockMvc the redirect url in the location header of a response

I'm testing an endpoint with MockMvc. This endpoints does a redirect at the end, so it's setting the redirect URL in the location header. This url has several params, so the resulting redirect url it's like this:

https://platform:8080/auth?scope=openid&response_type=id_token&response_mode=form_post&prompt=none&client_id=toolid&redirect_uri=https://localhost:8080/tool/token/receiver&login_hint=loginHint&state=1d73c90f-fe03-47dc-9e28-ed416fad7773&nonce=7b5e7240-161e-4d78-8e32-54923c9ce04a

I want to check that the 9 params are present at least. I'm thinking in something like:

mockMvc.perform(get(OIDC_INIT_FLOW_ENDPOINT)
                .contentType(MediaType.APPLICATION_FORM_URLENCODED)
                .params(initFlowRequestParams))
        .andExpect(status().isFound())
        .andExpect(header().exists(LOCATION))
        .andExpect(header().string(LOCATION, contains("openId")));

This piece of code doesn't work cause the last "andExpect" but it shows my intent. How can I do achieve my goal?

EDIT:

With the help of Chris I was able to find a solution for my enquiry:

mockMvc.perform(get(OIDC_INIT_FLOW_ENDPOINT).contentType(MediaType.APPLICATION_FORM_URLENCODED).params(initFlowRequestParams))
                .andExpect(status().isFound()).andExpect(header().exists(LOCATION)).andExpect(header().string(LOCATION,
                        Matchers.allOf(containsString("scope"), containsString("response_type"), containsString("response_type"),
                                containsString("prompt"), containsString("client_id"), containsString("redirect_uri"), containsString("login_hint"),
                                containsString("state"), containsString("nonce"))));

Upvotes: 4

Views: 648

Answers (1)

chris
chris

Reputation: 2621

Try using:

import static org.hamcrest.Matchers.containsString;

// ...
mockMvc.perform(get(OIDC_INIT_FLOW_ENDPOINT)
                 .contentType(MediaType.APPLICATION_FORM_URLENCODED)
                 .params(initFlowRequestParams))
        .andExpect(status().isFound())
        .andExpect(header().exists(LOCATION))
        .andExpect(header().string(LOCATION, containsString("openId")));

My hunch is that the contains method you are using is a Mockito argument matcher which leads you to the wrong overload of the string() match method. The overload you want to use expects a Hamcrest matcher.

Upvotes: 2

Related Questions