【问题标题】:spring rest testing @JsonFormat annotationspring rest测试@JsonFormat注解
【发布时间】: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) 添加到本地日期变量中。

标签: spring rest testing


【解决方案1】:

有了jackson-datatype-jsr310的依赖,其实它应该会自动格式化,不需要任何注解。当您确认您有这种依赖时,不确定为什么它没有给出正确的格式。确保它在运行时类路径中(干净的 .m2 目录:-) 并相信我有时会有所帮助。 )

其他你可以试试下面给出的代码。

 @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd-MM-yyy")
 @JsonDeserialize(using = LocalDateDeserializer.class)
 @JsonSerialize(using = LocalDateSerializer.class)
 private LocalDate birthdate;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-01-29
    • 2013-10-09
    • 1970-01-01
    • 2016-08-09
    • 2022-01-04
    • 2012-01-19
    • 2016-07-18
    • 1970-01-01
    相关资源
    最近更新 更多