【发布时间】:2018-02-25 16:53:07
【问题描述】:
我需要测试我的端点 /people 是否返回正确的 json 值。 我在我的 Person 模型中使用 `@JsonFormat 注释,当我使用 Postman 或浏览器时,它会以“dd-MM-yyyy”格式生成正确的日期。
例子:
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd-MM-yyy")
private LocalDate birthDate;
并且在 json 中输出是正确的-> birthDate: "01-01-2000"
但是如果我想测试我的控制器,它会产生以下错误:
Expected: is "01-01-2000"
but: was <{year=2000, month=JANUARY, monthValue=1, dayOfMonth=1,
chronology={id=ISO, calendarType=iso8601}, leapYear=true,
dayOfWeek=SATURDAY, dayOfYear=1, era=CE}>
我不知道问题出在哪里。 我的测试方法是这样的:
//given
Person testPerson = new Person("Jan", "Kowalski", LocalDate.of(2000, 1, 1),
LocalDate.of(2005, 12, 31), "123456");
List<Person> peopleList = Arrays.asList(testPerson);
//when
Mockito.when(personRepository.findAll()).thenReturn(peopleList);
//then
mockMvc.perform(get("/people"))
.andExpect(MockMvcResultMatchers.status().isOk())
.andExpect(MockMvcResultMatchers.content().contentType(MediaType.APPLICATION_JSON_UTF8))
.andExpect(MockMvcResultMatchers.jsonPath("$[0].birthDate", Matchers.is("01-01-2000"))));
提前致谢!
【问题讨论】:
-
你有jackson-datatype-jsr310依赖吗
-
@surya 是的,我有
-
尝试将@JsonSerialize(using = LocalDateSerializer.class) 添加到本地日期变量中。