【发布时间】:2021-07-26 16:26:46
【问题描述】:
我想对 Spring Boot 中的创建和更新 API 进行测试:
@Test
public void shouldCreateNewUser() throws Exception, UserAlreadyExistException {
User user = User.builder()
.id(10L)
.firstName("Alin")
.lastName("Balan")
.mail("alin@yahoo.com")
.password("pass")
.isAdmin(true)
.role(Roles.PTE)
.build();
mvc.perform(MockMvcRequestBuilders.post("/api/users")
.contentType(MediaType.APPLICATION_JSON)
.content(mapper.writeValueAsString(user)))
.andExpect(status().isOk())
.andExpect(MockMvcResultMatchers.jsonPath("$[10].id",is(10)));
Mockito.verify(userService, Mockito.times(1)).save(Mockito.any());
}
但是我有这个错误
java.lang.AssertionError:JSON 路径“$[10].id”处没有值,异常:json 不能为 null 或为空
【问题讨论】:
-
为什么要超过 10 个?
-
你。不希望值不存在时测试失败?
-
@Deadpool 我验证了这些字段..我创建了那个用户,我想验证它是否发布;没问题
-
为什么不这样:
jsonPath("$.id", is(10))? -
jsonPath("$.id", is(10))确实是正确的——他们似乎误解了jsonpath。查看基本指南here。
标签: java spring-boot jsonpath jayway