dimanche 22 octobre 2017

MockMvc saves Json with null fields in RestController test

The Context

I am working on small REST application in Spring Boot. I would like to perform test Controller (POST.METHOD) which add new object to database.

The Problem

I create new entity through constructor and I specify fields in my object. Then I save this object through MockMvc. And there is a problem, MockMvc saved my object, but all fields are null or false. Service which controller uses is tested and works properly

The Code

Controller:

    @RestController
    public class ParkingMeterController {

    @Autowired
    ParkingMeterService parkingMeterService;

    @PostMapping("parking-meter")
    public ParkingMeter addParkingMeter(){
        ParkingMeter parkingMeter = new ParkingMeter();
        return parkingMeterService.addNewParkingMeter(parkingMeter);
    }

Entity:

    @Entity
    @Component
    @Data
    public class ParkingMeter {

    @Id
    @GeneratedValue
    private long id;
    private boolean occupied = false;
    private Timestamp startTime;
    private Timestamp endTime;

    public ParkingMeter() {
    }

    public ParkingMeter(boolean occupied, Timestamp startTime, Timestamp endTime) {
        this.occupied = occupied;
        this.startTime = startTime;
        this.endTime = endTime;
    }
}

Test class:

    @RunWith(SpringRunner.class)
    @SpringBootTest
    @AutoConfigureMockMvc
    public class ParkingMeterControllerTest {

    @Autowired
    private MockMvc mvc;
    @Autowired
    ParkingMeterService parkingMeterService;

    @Test
    public void shouldAddNewParkingMeter() throws Exception {
        ParkingMeter parkingMeter = new ParkingMeter(true, new Timestamp(0), new Timestamp(5000));
        String json = new Gson().toJson(parkingMeter);
        System.out.println(json);

        mvc.perform(post("/parking-meter/")
                .contentType(MediaType.APPLICATION_JSON_UTF8)
                .content(json)
                .accept(MediaType.APPLICATION_JSON_UTF8))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.id", is(3)))
                .andExpect(jsonPath("$.startTime", is(new Timestamp(0))));
    }

System out print result:

{"id":0,"occupied":true,"startTime":"Jan 1, 1970 1:00:00 AM","endTime":"Jan 1, 1970 1:00:05 AM"}

MockServletResponse:

MockHttpServletResponse:
           Status = 200
    Error message = null
          Headers = {Content-Type=[application/json;charset=UTF-8]}
     Content type = application/json;charset=UTF-8
             Body = {"id":3,"occupied":false,"startTime":null,"endTime":null}
    Forwarded URL = null
   Redirected URL = null
          Cookies = []

As you can see above. In Mock servlet resposne we can see Body with null and false fields which are different from those I have defined.

Thanks in advance.

Aucun commentaire:

Enregistrer un commentaire