[英]Unit Test - Using MockMvc to test the controller with @RequestHeader with HashMap
我有一个具有以下结构的 controller:
@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"));
...
...
}
}
我正在使用 MockMvc 为这个 controller 编写单元测试:
@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();
...
...
}
}
由于MockMvcRequestBuilders
的header
方法只接受字符串,我不确定如何使用 MockMvc 来测试我的 controller ,它有Map<String, String>
作为@RequestHeader
。 任何帮助将不胜感激!
还有另一种方法,如下所示(.headers(*)),您可以使用它,只需验证。
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();
希望这是有用的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.