mockMVC method GET java.lang.AssertionError: Status Expected :200 Actual :500

mockMVC method GET java.lang.AssertionError: Status Expected :200 Actual :500

我用 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方法测试:

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

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

看来您没有找到问题所在的正确位置。

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

Request URI = /users/1

并且您的测试方法试图获得 /account/1:

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

至于错误本身,MethodArgumentTypeMismatchException:

Exception that indicates that a method argument has not the expected type.

也就是说@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) 方法。

祝你好运!