Linked Questions

Popular Questions

I would like to test a POST method for the RESTful API provided below,

@PostMapping(value = "/createAppointment", consumes = "application/json;charset=UTF-8", produces = "application/json;charset=UTF-8")
    @JsonDeserialize(as = Boolean.class)
    public ResponseEntity<Appointment> createAppointment(@RequestBody Appointment appointment) {

        appointment.setStatus(new Status(true));

        service.save(appointment);
        return ResponseEntity.status(HttpStatus.CREATED).body(appointment);
    }

I write the test provides below,

@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.MOCK)
@AutoConfigureMockMvc
public class AppointmentAPITest {


    /*
     * we need a system to simulate this behavior without starting a
     * full HTTP server. MockMvc is the Spring class that does that.
     * */
    @Autowired
    private MockMvc mockMvc;

    @MockBean
    private AppointmentAPI api;




    @Test
    public void createAppointment_thenReturnTheAppointment() throws Exception {

        Appointment appoint1 = new Appointment(Date.valueOf("2018-09-01"), Time.valueOf("01:12:16"), "Vania Vong", 125.5);

        mockMvc.perform(post("http://localhost:8080/api/v1/appointments/createAppointment")
                .contentType(MediaType.APPLICATION_JSON)
                .content(TestUtil.convertObjectToJsonBytes(appoint1))
        )
                .andExpect(status().isOk())
//                .andExpect(content().contentTypeCompatibleWith("application/json"))
                .andExpect(content().contentType(MediaType.APPLICATION_JSON))
                .andExpect(jsonPath("$.id", is(appoint1.getId())))
                .andExpect(jsonPath("$.name_of_doctor", is(appoint1.getName_of_doctor())))
                .andExpect(jsonPath("$.appointment_date", is(appoint1.getAppointment_date().toString())))
                .andExpect(jsonPath("$.created_at", is(appoint1.getCreated_at().toString())))
                .andExpect(jsonPath("$.status", is(appoint1.getStatus())))
                .andExpect(jsonPath("$.price", is(appoint1.getPrice())));


    }
}

The error I get is here,

MockHttpServletRequest:
      HTTP Method = POST
      Request URI = /api/v1/appointments/createAppointment
       Parameters = {}
          Headers = [Content-Type:"application/json;charset=UTF-8"]
             Body = {"created_at":"01:12:16","appointment_date":1535752800000,"name_of_doctor":"Vania Vong","price":125.5}
    Session Attrs = {}

Handler:
             Type = com.appoint.manager.Appointment.api.AppointmentAPI$MockitoMock$952870826
           Method = public org.springframework.http.ResponseEntity<com.appoint.manager.Appointment.models.Appointment> com.appoint.manager.Appointment.api.AppointmentAPI$MockitoMock$952870826.createAppointment(com.appoint.manager.Appointment.models.Appointment)

Async:
    Async started = false
     Async result = null

Resolved Exception:
             Type = null

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

FlashMap:
       Attributes = null

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

java.lang.AssertionError: Content type not set

    at org.springframework.test.util.AssertionErrors.fail(AssertionErrors.java:36)
    at org.springframework.test.util.AssertionErrors.assertTrue(AssertionErrors.java:66)
    at org.springframework.test.web.servlet.result.ContentResultMatchers.lambda$contentType$0(ContentResultMatchers.java:80)
    at org.springframework.test.web.servlet.MockMvc$1.andExpect(MockMvc.java:195)
    at com.appoint.manager.Appointment.api.AppointmentAPITest.createAppointment_thenReturnTheAppointment(AppointmentAPITest.java:127)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
    at org.springframework.test.context.junit4.statements.RunBeforeTestExecutionCallbacks.evaluate(RunBeforeTestExecutionCallbacks.java:74)
    at org.springframework.test.context.junit4.statements.RunAfterTestExecutionCallbacks.evaluate(RunAfterTestExecutionCallbacks.java:84)
    at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75)
    at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86)
    at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:251)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:97)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
    at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:190)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
    at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
    at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
    at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
    at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)

I use the class to convert the Object to the JSON,

public class TestUtil {

    public static final MediaType APPLICATION_JSON_UTF8 = new MediaType(MediaType.APPLICATION_JSON.getType(), MediaType.APPLICATION_JSON.getSubtype(), Charset.forName("utf8"));

    private static final String CHARACTER = "a";

    public static byte[] convertObjectToJsonBytes(Object object) throws IOException {
        ObjectMapper mapper = new ObjectMapper();
        mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        return mapper.writeValueAsBytes(object);
    }

    public static String createStringWithLength(int length) {
        StringBuilder builder = new StringBuilder();

        for (int index = 0; index < length; index++) {
            builder.append(CHARACTER);
        }

        return builder.toString();
    }
}

Why does it provide the message of java.lang.AssertionError: Content type not set and how do I write the POST method test correctly?

Here is the cURL call which works successfully and I provide if this helps to asnwer,

$ curl -i -X POST -H "Content-Type:application/json" -d "{\"created_at\" : \"01:12:16\",\"appointment_date\" : \"2018-10-05\",\"name_of_doctor\" : \"Monika\", \"price\": \"122.5\"}" http://localhost:8080/api/v1/appointments/createAppointment

As an experiment, I changed the code to this and still have the same error,

@PostMapping(value = "/createAppointment", consumes = "application/json;charset=UTF-8", produces = "application/json;charset=UTF-8")
    @JsonDeserialize(as = Boolean.class)
    public ResponseEntity<Appointment> createAppointment(@RequestBody Appointment appointment) {

        appointment.setStatus(new Status(true));

        service.save(appointment);

        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Type", "application/json; charset=utf-8");
        return new ResponseEntity<Appointment>(appointment, headers, HttpStatus.OK);

//        return ResponseEntity.status(HttpStatus.CREATED).body(appointment);
    }

Related Questions