简体   繁体   中英

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!

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.

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