gpt4 book ai didi

java - Spring MockMvc - 如何测试 REST Controller 的删除请求?

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:08:13 26 4
gpt4 key购买 nike

我需要测试我的 Controller 方法,包括删除方法。这是部分 Controller 代码:

@RestController
@RequestMapping("/api/foo")
public class FooController {

@Autowired
private FooService fooService;

// other methods which works fine in tests

@RequestMapping(path="/{id}", method = RequestMethod.DELETE)
public void delete(@PathVariable Long id) {
fooService.delete(id);
}
}

这是我的测试:

@InjectMocks
private FooController fooController;

@Before
public void setUp() {
this.mockMvc = MockMvcBuilders.standaloneSetup(fooController)
.setControllerAdvice(new ExceptionHandler()).alwaysExpect(MockMvcResultMatchers.content().contentType("application/json;charset=UTF-8")).build();
}

@Test
public void testFooDelete() throws Exception {
this.mockMvc.perform(MockMvcRequestBuilders
.delete("/api/foo")
.param("id", "11")
.contentType(MediaType.APPLICATION_JSON))
.accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk());
}

由于状态码不正确,测试以失败告终:

java.lang.AssertionError: Status Expected :200 Actual :400

在控制台日志中我还发现了这个:

2017-12-11 20:11:01 [main] DEBUG o.s.t.w.s.TestDispatcherServlet - DispatcherServlet with name '' processing DELETE request for [/api/foo]
2017-12-11 20:11:01 [main] DEBUG o.s.w.s.m.m.a.RequestMappingHandlerMapping - Looking up handler method for path /api/foo
2017-12-11 20:11:01 [main] DEBUG o.s.w.s.m.m.a.ExceptionHandlerExceptionResolver - Resolving exception from handler [null]: org.springframework.web.HttpRequestMethodNotSupportedException: Request method 'DELETE' not supported
2017-12-11 20:11:01 [main] DEBUG o.s.w.s.m.m.a.ExceptionHandlerExceptionResolver - Invoking @ExceptionHandler method: public org.springframework.http.ResponseEntity<java.util.Map<java.lang.String, java.lang.Object>> cz.ita.javaee.web.controller.error.ExceptionHandler.handleException(java.lang.Exception)
2017-12-11 20:11:01 [main] DEBUG o.s.w.s.m.m.a.HttpEntityMethodProcessor - Written [{stackTrace=org.springframework.web.HttpRequestMethodNotSupportedException: Request method 'DELETE' not supported

你能告诉我如何解决吗?谢谢。

最佳答案

你的目标 URI 是:/api/foo/11 基于这个根:/api/foo 和这个路径变量:/{id}.

当使用 MockMvc 时,您可以像这样设置路径变量(又名 URI 变量):

delete(uri, uriVars)

更多详情 in the Javadocs .

因此,您的测试应为:

@Test
public void testFooDelete() throws Exception {
this.mockMvc.perform(MockMvcRequestBuilders
.delete("/api/foo/{id}", "11")
.contentType(MediaType.APPLICATION_JSON))
.accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk());
}

或者:

@Test
public void testFooDelete() throws Exception {
this.mockMvc.perform(MockMvcRequestBuilders
.delete("/api/foo/11")
.contentType(MediaType.APPLICATION_JSON))
.accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk());
}

关于java - Spring MockMvc - 如何测试 REST Controller 的删除请求?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47759833/

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