gpt4 book ai didi

spring-mvc - mockMvc - 测试错误消息

转载 作者:行者123 更新时间:2023-12-03 01:26:17 26 4
gpt4 key购买 nike

有人有任何提示,或者有人知道如何测试 HTTP 响应对象返回的“错误消息”吗?

@Autowired
private WebApplicationContext ctx;

private MockMvc mockMvc;

@Before
public void setUp() throws Exception {
mockMvc = MockMvcBuilders.webAppContextSetup(ctx).build();
}

回应:

MockHttpServletResponse:
Status = 200
Error message = null
Headers = {Content-Type=[application/json;charset=UTF-8]}
Content type = application/json;charset=UTF-8

最佳答案

您可以使用方法status.reason() .

例如:

     @Test
public void loginWithBadCredentials() {
this.mockMvc.perform(
post("/rest/login")
.contentType(MediaType.APPLICATION_JSON)
.content("{\"username\": \"baduser\", \"password\": \"invalidPassword\"}")
)
.andDo(MockMvcResultHandlers.print())
.andExpect(status().isUnauthorized())
.andExpect(status().reason(containsString("Bad credentials")))
.andExpect(unauthenticated());
}


MockHttpServletResponse:
Status = 401
Error message = Authentication Failed: Bad credentials
Content type = null
Body =
Forwarded URL = null
Redirected URL = null
Cookies = []

关于spring-mvc - mockMvc - 测试错误消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25288930/

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