lovprogramming
lovprogramming

Reputation: 653

Unit Test - Using MockMvc to test the controller with @RequestHeader with HashMap

I have a controller that has the following structure:

@RequestMapping(value="/validate", method=RequestMethod.POST)
    public ResponseEntity<Jwt> IsValid(@RequestBody UserRequest userRequest, @RequestHeader Map<String, String> header) throws Exception {
    if(header.contains("key") && header.contains("secret") {
        process(header.get("key"), header.get("secret"));
        ...
        ...
    }
} 

I'm writing a unit test for this controller using MockMvc:

@RunWith(SpringRunner.class)
@AutoConfigureMockMvc
@SpringBootTest
public class AuthenticatorServiceTest {

    @Autowired
    private MockMvc mockMvc;

    @Test
    public void CorrectKeyValidation throws Exception {
        String key = "correct-key";
        String secret = "correct-secret";
        Map<String, String> map = new HashMap<>();
        map.put("key", key);
        map.put("secret", secret);

        MvcResult result = mockMvc.perform(MockMvcRequestBuilders.post("/validate")
                .header() // <- doesn't accept Map here.
                .contentType(MediaType.APPLICATION_JSON))
                .andExpect(status().isOk()).andReturn();
        ...
        ... 
    }  
} 

Since the header method for MockMvcRequestBuilders only accepts string, Im not really sure how to use MockMvc to test my controller which has Map<String, String> as a @RequestHeader. Any help would be greatly appreciated!

Upvotes: 0

Views: 5915

Answers (1)

Ajeet Maurya
Ajeet Maurya

Reputation: 660

There is another method like below (.headers(*)), you can use that , just verified.

Map<String, String> map = new HashMap<>();
        map.put("key", key);
        map.put("secret", secret);
HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.setAll(map);
        MvcResult result = mvc.perform(MockMvcRequestBuilders
                .post("/scheduler/enable")
                .headers(httpHeaders)
                .contentType(MediaType.APPLICATION_JSON_UTF8)
                .content(this.getRequstAsJSON()))
                .andDo(print())
                .andReturn();

Hope this is useful.

Upvotes: 3

Related Questions