Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

spring rest testing @JsonFormat annotation

I need to test if my endpoint /people return correct json values. I use in my Person model `@JsonFormat annotation, when I use Postman or browser it produces correct date in format "dd-MM-yyyy".

Example:

@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd-MM-yyy")
private LocalDate birthDate;

And output is correct in json-> birthDate: "01-01-2000"

But if I want to test my controller, it produces me following error:

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}>

I don't know where is the problem. My test method looks like this:

//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"))));

Thanks in advance!

like image 364
jeremy Avatar asked Mar 14 '26 03:03

jeremy


1 Answers

With jackson-datatype-jsr310 dependecy, actually it should automatically format , and you dont need any annotation. As you confirmed that you have that dependecy, not sure why its not giving correct format.Make sure its there in runtime classpath (clean .m2 directory :-) and believe me sometime it helps. )

Othersie you can try code as given below.

 @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd-MM-yyy")
 @JsonDeserialize(using = LocalDateDeserializer.class)
 @JsonSerialize(using = LocalDateSerializer.class)
 private LocalDate birthdate;
like image 88
surya Avatar answered Mar 16 '26 18:03

surya



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!