Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/spring/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
springrest测试@JsonFormat注释_Spring_Rest_Testing - Fatal编程技术网

springrest测试@JsonFormat注释

springrest测试@JsonFormat注释,spring,rest,testing,Spring,Rest,Testing,我需要测试我的端点/人是否返回正确的json值。 我在我的个人模型中使用了`@JsonFormat注释,当我使用邮递员或浏览器时,它会以“dd-MM-yyyy”格式生成正确的日期 例如: @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd-MM-yyy") private LocalDate birthDate; 输出在json中是正确的->生日:“01-01-2000” 但如果我想测试我的控制器,它会产生以下错误: Expec

我需要测试我的端点/人是否返回正确的json值。 我在我的个人模型中使用了`@JsonFormat注释,当我使用邮递员或浏览器时,它会以“dd-MM-yyyy”格式生成正确的日期

例如:

@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd-MM-yyy")
private LocalDate birthDate;
输出在json中是正确的->
生日:“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}>
预期:is“01-01-2000”
但是:是吗
我不知道问题出在哪里。 我的测试方法如下所示:

//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"))));
//给定
Person testPerson=新人(“Jan”,“Kowalski”,LocalDate.of(2000,1,1),
本地日期(2005年12月31日),“123456”);
List peopleList=Arrays.asList(testPerson);
//什么时候
Mockito.when(personRepository.findAll()).thenReturn(peopleList);
//然后
mockMvc.perform(get(“/people”))
.andExpect(MockMvcResultMatchers.status().isOk())
.andExpect(MockMvcResultMatchers.content().contentType(MediaType.APPLICATION\u JSON\u UTF8))
.andExpect(MockMvcResultMatchers.jsonPath(“$[0].生日”),Matchers.is(“01-01-2000”);

提前谢谢

使用jackson-datatype-jsr310 dependecy,实际上它应该自动格式化,并且您不需要任何注释。当您确认有这种依赖关系时,不确定为什么它没有给出正确的格式。请确保它在运行时类路径(clean.m2目录:-)中,相信我,有时它会有所帮助。)

另外,您可以尝试下面给出的代码

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

你们有jackson-datatype-jsr310吗dependency@surya是的,我已经尝试将@JsonSerialize(使用=LocalDateSerializer.class)添加到localdate变量。