【问题标题】:mockMVC method GET java.lang.AssertionError: Status Expected :200 Actual :500mockMVC 方法 GET java.lang.AssertionError:预期状态:200 实际:500
【发布时间】:2018-10-23 11:32:12
【问题描述】:

我在spring mockMVC中写了一个测试这个方法:

我的方法测试是:

@Test
public void getAccount()throws Exception {
     mockMvc.perform(get("/account/1"))
            .andDo(print())
            .andExpect(status().isOk())
            .andExpect(view().name("/account/"));
}

我有以下错误:

MockHttpServletRequest:
      HTTP Method = GET
      Request URI = /users/1
       Parameters = {}
          Headers = {}
             Body = <no character encoding set>
    Session Attrs = {}
Async:
    Async started = false
     Async result = null

Resolved Exception:
             Type = org.springframework.web.method.annotation.MethodArgumentTypeMismatchException

ModelAndView:
        View name = null
             View = null
            Model = null
FlashMap:
       Attributes = null

MockHttpServletResponse:
           Status = 500
    Error message = null
          Headers = {Content-Type=[text/plain;charset=ISO-8859-1], Content-Length=[14]}
     Content type = text/plain;charset=ISO-8859-1
             Body = We are doomed.
    Forwarded URL = null
   Redirected URL = null
          Cookies = []

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

这是我的 POST 方法测试:

我的测试方法有什么问题?我可以解决这个问题吗?

我正在寻求帮助和快速答复

【问题讨论】:

    标签: spring spring-boot junit mockmvc


    【解决方案1】:

    看来您没有找到解决问题的正确位置。

    记录器输出请求 URI /users/1 有错误:

    Request URI = /users/1
    

    而您的测试方法正在尝试获取/account/1

    mockMvc.perform(get("/account/1"))
    

    至于错误本身,MethodArgumentTypeMismatchException:

    表示方法参数不是预期类型的​​异常。

    也就是说@GetMapping("/users/{id}")注解的方法有错误的@PathVariable参数类型。

    在您的情况下,您使用 UUID 作为参数:

    public @ResponseBody ResponseEntity<AccountDTO> getAccount(@PathVariable UUID id) {
    

    但是,在您的测试中,您没有传递 UUID,而是在测试中传递了一个数值 (long/int)。

    如果要生成随机UUID,可以使用UUID.randomUUID()

    @Test
    public void getAccount()throws Exception {
         mockMvc.perform(get("/account/" + UUID.randomUUID()))
                .andDo(print())
                .andExpect(status().isOk())
                .andExpect(view().name("/account/"));
    }
    

    或者,您可以在映射方法中使用 long 而不是 uuid:

    @GetMapping(value = "/{id}")
    @ApiOperation(value = "Retrieve account.")
    public @ResponseBody ResponseEntity<AccountDTO> getAccount(@PathVariable Long id) {
        return accountService.retreiveById(id).map(ResponseEntity::ok)
                .orElseGet(() -> ResponseEntity.notFound().build());
    }
    

    虽然在这种情况下,您可能必须更改您的 AccountService.retrieveById(id) 方法。

    祝你好运!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-08-05
      • 2017-12-25
      • 1970-01-01
      • 1970-01-01
      • 2017-01-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多