vendredi 26 mars 2021

POST method test in spring. Code 400 instead of 201

I am creating an application where I can create a car object. Car class without setters and getters:

package github.KarolXX.demo.model;


import org.hibernate.annotations.GenericGenerator;

import javax.persistence.*;
import javax.validation.constraints.NotBlank;
import java.time.LocalDateTime;

@Entity
@Table(name = "cars")
public class Car {
    @Id
    @GeneratedValue(generator = "inc")
    @GenericGenerator(name = "inc", strategy = "increment")
    private int id;
    @NotBlank(message = "car name`s must be not empty")
    private String name;
    private LocalDateTime productionYear;
    private boolean tested;

    public Car() {
    }

    public Car(@NotBlank(message = "car name`s must be not empty") String name, LocalDateTime productionYear) {
        this.name = name;
        this.productionYear = productionYear;
    }
}

I would like to know how to test the POST method in Spring. Below is a code snippet for the POST method which just create Java object named Car (first snippet)

 @PostMapping("/cars")
ResponseEntity<Car> createCar(@RequestBody @Valid Car newCar) {
    logger.info("Creating new car");
    var result = repository.save(newCar);
    return ResponseEntity.created(URI.create("/" + result.getId())).body(result);
}

I am trying to test it this way:

package github.KarolXX.demo.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import github.KarolXX.demo.TestConfiguration;
import github.KarolXX.demo.model.Car;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultHandlers;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;

import java.time.LocalDateTime;

import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

@SpringBootTest
@AutoConfigureMockMvc
@ActiveProfiles("integration")
class CarControllerIntegrationServerSideTest {
    @Autowired
    private MockMvc mockMvc;    

    @Test
    public void httpPost_createsNewCar_returnsCreatedCar() throws Exception {
        //given
        Car car = new Car("second server side test", LocalDateTime.parse("2021-01-02T13:34:54"));

        //when + then
        mockMvc.perform(post("/cars")
                .content(asJsonString(car))
                .contentType(MediaType.APPLICATION_JSON)
                .accept(MediaType.APPLICATION_JSON))
                .andDo(MockMvcResultHandlers.print())
                .andExpect(status().isCreated());
    }

    public static String asJsonString(final Car objectCar) {
        try {
            return new ObjectMapper().writeValueAsString(objectCar);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return null;
    }
}



   

I did it based on this article Unfortunately my test does not pass. Although in the logs I can see that the request body and the request headers are set correctly, I get the status 400

2021-03-26 12:05:01.532  WARN 10696 --- [           main] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Expected array or string.; nested exception is com.fasterxml.jackson.databind.exc.MismatchedInputException: Expected array or string.
 at [Source: (PushbackInputStream); line: 1, column: 59] (through reference chain: github.KarolXX.demo.model.Car["productionYear"])]

MockHttpServletRequest:
      HTTP Method = POST
      Request URI = /cars
       Parameters = {}
          Headers = [Content-Type:"application/json;charset=UTF-8", Accept:"application/json", Content-Length:"279"]
             Body = {"id":0,"name":"second server side test","productionYear":{"month":"JANUARY","dayOfWeek":"SATURDAY","dayOfYear":2,"nano":0,"year":2021,"monthValue":1,"dayOfMonth":2,"hour":13,"minute":34,"second":54,"chronology":{"id":"ISO","calendarType":"iso8601"}},"tested":false,"brand":null}
    Session Attrs = {}

Handler:
             Type = github.KarolXX.demo.controller.CarController
           Method = github.KarolXX.demo.controller.CarController#createCar(Car)

Async:
    Async started = false
     Async result = null

Resolved Exception:
             Type = org.springframework.http.converter.HttpMessageNotReadableException

ModelAndView:
        View name = null
             View = null
            Model = null

FlashMap:
       Attributes = null

MockHttpServletResponse:
           Status = 400
    Error message = null
          Headers = []
     Content type = null
             Body = 
    Forwarded URL = null
   Redirected URL = null
          Cookies = []

MockHttpServletRequest:
      HTTP Method = POST
      Request URI = /cars
       Parameters = {}
          Headers = [Content-Type:"application/json;charset=UTF-8", Accept:"application/json", Content-Length:"279"]
             Body = {"id":0,"name":"second server side test","productionYear":{"month":"JANUARY","dayOfWeek":"SATURDAY","dayOfYear":2,"nano":0,"year":2021,"monthValue":1,"dayOfMonth":2,"hour":13,"minute":34,"second":54,"chronology":{"id":"ISO","calendarType":"iso8601"}},"tested":false,"brand":null}
    Session Attrs = {}

Handler:
             Type = github.KarolXX.demo.controller.CarController
           Method = github.KarolXX.demo.controller.CarController#createCar(Car)

Async:
    Async started = false
     Async result = null

Resolved Exception:
             Type = org.springframework.http.converter.HttpMessageNotReadableException

ModelAndView:
        View name = null
             View = null
            Model = null

FlashMap:
       Attributes = null

MockHttpServletResponse:
           Status = 400
    Error message = null
          Headers = []
     Content type = null
             Body = 
    Forwarded URL = null
   Redirected URL = null
          Cookies = []

java.lang.AssertionError: Status expected:<201> but was:<400>
Expected :201
Actual   :400

I have no idea what could be wrong but when I change this line of code mockMvc.perform(post("/cars") to this one mockMvc.perform(post("/") then I got status 404

Aucun commentaire:

Enregistrer un commentaire