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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/47759833/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 09:47:50  来源:igfitidea点击:

Spring MockMvc - How to test delete request of REST controller?

javaspringrestmockitospring-test-mvc

提问by Denis Stephanov

I need to test my controller methods including a delete method. Here is partial controller code:

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

@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);
    }    
}

And here is my test:

这是我的测试:

@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());
}

Test finish with failure because incorrect status code:

测试完成失败,因为状态代码不正确:

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

java.lang.AssertionError:预期状态:200 实际:400

In console log I also found this:

在控制台日志中,我还发现了这一点:

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

Can you tell me how to fix it? Thanks.

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

回答by glytching

Your target URI is: /api/foo/11based on this root: /api/fooand this path variable: /{id}.

您的目标 URI 是:/api/foo/11基于此根:/api/foo和此路径变量:/{id}

When using MockMvcyou set path variables (aka URI variables) like so:

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

delete(uri, uriVars)

More details in the Javadocs.

Javadocs 中的更多详细信息。

So, your test should read:

所以,你的测试应该是:

@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());
}

Or alternatively:

或者:

@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());
}