gpt4 book ai didi

java - 使用 Spring mockMvc 测试可选路径变量

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:39:43 25 4
gpt4 key购买 nike

我在 Spring MVC 中有一个带有可选路径变量的方法。我正在尝试在未提供可选路径变量的情况下对其进行测试。

来自 Controller 的片段,要调用的资源 URI-

@RequestMapping(value = "/some/uri/{foo}/{bar}", method = RequestMethod.PUT)
public <T> ResponseEntity<T> someMethod(
@PathVariable("foo") String foo,
@PathVariable(value = "bar", required = false) String bar
) {
LOGGER.info("foo: {}, bar: {}", foo, bar);
}

我使用 MockMvc 进行的测试的片段-

//inject context
@Autowired
private WebApplicationContext webApplicationContext;

protected MockMvc mockMvc;

@Before
public void setup() {
//build mockMvc
mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
}

@Test
public void someMethodTest() throws Exception {
//works as expected
mockMvc.perform(put("/some/uri/{foo}/{bar}", "foo", "bar"))
.andExpect(status().isOk()); //works

//following doesn't work

//pass null for optional
mockMvc.perform(put("/some/uri/{foo}/{bar}", "foo", null))
.andExpect(status().isOk()); //throws 404

//pass empty for optional
mockMvc.perform(put("/some/uri/{foo}/{bar}", "foo", ""))
.andExpect(status().isOk()); //throws 404

//remove optional from URI
mockMvc.perform(put("/some/uri/{foo}", "foo"))
.andExpect(status().isOk()); //throws 404
}

最佳答案

像这样使用 @RequestMapping 值数组 ...

@RequestMapping(
value = {"/some/uri/{foo}", "/some/uri/{foo}/{bar}"},
method = RequestMethod.PUT)
public ResponseEntity<String> someMethod(
@PathVariable("foo") String foo,
@PathVariable(value = "bar", required = false) String bar
) {
return new ResponseEntity<>(foo + " and " + (bar == null ? "<null>" : bar), HttpStatus.OK);
}

...将使该测试通过:

@Test
public void someMethodTest() throws Exception {
MvcResult mvcResult = mockMvc.perform(put("/some/uri/{foo}/{bar}", "foo", "bar"))
.andExpect(status().isOk()).andReturn();
Assert.assertEquals("foo and bar", mvcResult.getResponse().getContentAsString());

mvcResult = mockMvc.perform(put("/some/uri/{foo}/{bar}", "foo", null))
.andExpect(status().isOk()).andReturn();
Assert.assertEquals("foo and <null>", mvcResult.getResponse().getContentAsString());

mvcResult = mockMvc.perform(put("/some/uri/{foo}/{bar}", "foo", ""))
.andExpect(status().isOk()).andReturn();
Assert.assertEquals("foo and <null>", mvcResult.getResponse().getContentAsString());

mvcResult = mockMvc.perform(put("/some/uri/{foo}", "foo"))
.andExpect(status().isOk()).andReturn();
Assert.assertEquals("foo and <null>", mvcResult.getResponse().getContentAsString());
}

这似乎是最简单的解决方案,而且它可能对 Swagger 等工具更友好,因为它使映射显式化。

但是,您也可以声明通配符映射,然后在 Controller 方法中使用路径匹配器来解释请求 URI。比如这个方法...

private final AntPathMatcher antPathMatcher = new AntPathMatcher();

@RequestMapping(value = "/some/uri/with/wildcards/**", method = RequestMethod.PUT)
public ResponseEntity<String> someMethod(HttpServletRequest request) {
String matched = antPathMatcher.extractPathWithinPattern(
(String) request.getAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE), request.getPathInfo());
// ugly parsing code to read the path variables, allowing for the optionality of the second one
String foo = matched;
String bar = null;
String[] pathVariables = matched.split("/");
if (pathVariables.length > 1) {
foo = pathVariables[0];
bar = pathVariables[1];
}
return new ResponseEntity<>(foo + " and " + (bar == null ? "<null>" : bar), HttpStatus.OK);
}

...将使该测试通过:

@Test
public void someMethodTestWithWildcards() throws Exception {
MvcResult mvcResult = mockMvc.perform(put("/some/uri/with/wildcards/{foo}/{bar}", "foo", "bar"))
.andExpect(status().isOk()).andReturn();
Assert.assertEquals("foo and bar", mvcResult.getResponse().getContentAsString());

mvcResult = mockMvc.perform(put("/some/uri/with/wildcards/{foo}/{bar}", "foo", null))
.andExpect(status().isOk()).andReturn();
Assert.assertEquals("foo and <null>", mvcResult.getResponse().getContentAsString());

mvcResult = mockMvc.perform(put("/some/uri/with/wildcards/{foo}/{bar}", "foo", ""))
.andExpect(status().isOk()).andReturn();
Assert.assertEquals("foo and <null>", mvcResult.getResponse().getContentAsString());

mvcResult = mockMvc.perform(put("/some/uri/with/wildcards/{foo}", "foo"))
.andExpect(status().isOk()).andReturn();
Assert.assertEquals("foo and <null>", mvcResult.getResponse().getContentAsString());
}

关于java - 使用 Spring mockMvc 测试可选路径变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45825955/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com