Spring MockMvc -如何测试REST控制器的删除请求?

zdwk9cvp  于 2023-08-02  发布在  Spring
关注(0)|答案(2)|浏览(98)

我需要测试我的控制器方法,包括删除方法。以下是部分控制器代码:

@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:预期状态:200实际: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


你能告诉我怎么修吗?- 谢谢-谢谢

arknldoa

arknldoa1#

您的目标URI是:/api/foo/11基于此根:/api/foo和这个路径变量:/{id}的值。
当使用MockMvc时,您可以像这样设置路径变量(也称为URI变量):

delete(uri, uriVars)

字符串
在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());
}

t0ybt7op

t0ybt7op2#

前面的答案肯定是正确的:)但是如果你想测试204响应代码:

@Test
public void testFooDelete() throws Exception {
    ...
    .andExpect(status().isNoContent());
}

字符串
你可以通过**@ResponseStatus**显式地说出delete方法应该返回什么:

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

相关问题