2

Please help me out in solving the error. I want to test my Rest Controller using MockMvc but after testing i am getting the above error.

My GetTest is getting successfully run but my POST test is throwing out error. Maybe the way I have written the POST MVC test is not correct. Below is the whole code if need any other information please comment.

@RestController
public class Controller {

       @Autowired
       StudentRepository studentRepository;

       @RequestMapping(method= RequestMethod.POST,value="/students" ,consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
        public void addTopic(@RequestBody Student student){

            studentRepository.addStudent(student);
        }

}

The unit test class:

@RunWith(SpringRunner.class)
@WebMvcTest
public class TestingApplicationTests {

    @Autowired
    private MockMvc mvc;

    @MockBean
    private StudentRepository studentRepository;


    @Test
    public void firstTest() throws Exception {

        Student stud = new Student("Niladri", "nila", "asda");
        Student stud1 = new Student("Abhirup", "abhi", "asda");
        Student stud2 = new Student("Satarupa", "sata", "asda");

        List<Student> list = Arrays.asList(stud, stud1, stud2);

       given(studentRepository.getAll()).willReturn(list);


        mvc.perform(get("/students"))
            .andExpect(status().isOk())
            .andExpect(MockMvcResultMatchers.jsonPath("$", hasSize(3)));

    }

    @Test
    public void secondTest() throws Exception {

         Student student1=new Student("Niladri","Ni","seventy");
         String expectedJson=this.mapToJson(student1);

        mvc.perform(post("/students").contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON).content(expectedJson))
            .andExpect(status().isOk());


    }
    //Maps an object into a JSON String . Uses a JackSon ObjectMapper
    private String mapToJson(Object student1) throws JsonProcessingException {

        ObjectMapper objectMapper = new ObjectMapper();
        return objectMapper.writeValueAsString(student1);

    }
}

My First test is successfully getting completed(i.e get) but my second test(i.e POST) fails with below error:

Below are the logs.

2018-01-19 16:10:22.640  INFO 13348 --- [           main] c.test.Testing.TestingApplicationTests   : Starting TestingApplicationTests on 114983-T470p with PID 13348 (started by nchanda in C:\Users\nchanda\Downloads\Testing)
2018-01-19 16:10:22.641  INFO 13348 --- [           main] c.test.Testing.TestingApplicationTests   : No active profile set, falling back to default profiles: default
2018-01-19 16:10:22.655  INFO 13348 --- [           main] o.s.w.c.s.GenericWebApplicationContext   : Refreshing org.springframework.web.context.support.GenericWebApplicationContext@52719fb6: startup date [Fri Jan 19 16:10:22 IST 2018]; root of context hierarchy
2018-01-19 16:10:23.622  INFO 13348 --- [           main] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for @ControllerAdvice: org.springframework.web.context.support.GenericWebApplicationContext@52719fb6: startup date [Fri Jan 19 16:10:22 IST 2018]; root of context hierarchy
2018-01-19 16:10:23.678  INFO 13348 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/students]}" onto public java.util.List<com.test.Testing.Student> com.test.Testing.Controller.student()

or perhaps need to add/enable type information?)

at [Source: java.io.PushbackInputStream@70242f38; line: 1, column: 2]

MockHttpServletRequest:
      HTTP Method = GET
      Request URI = /students
       Parameters = {}
          Headers = {}

Handler:
             Type = com.test.Testing.Controller
           Method = public java.util.List<com.test.Testing.Student> com.test.Testing.Controller.student()

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=[application/json;charset=UTF-8]}
     Content type = application/json;charset=UTF-8
             Body = [{"name":"Niladri","id":"nila","marks":"asda"},{"name":"Abhirup","id":"abhi","marks":"asda"},{"name":"Satarupa","id":"sata","marks":"asda"}]
    Forwarded URL = null
   Redirected URL = null
          Cookies = []

MockHttpServletRequest:
      HTTP Method = POST
      Request URI = /students
       Parameters = {}
          Headers = {Content-Type=[application/json], Accept=[application/json]}

Handler:
             Type = com.test.Testing.Controller
           Method = public void com.test.Testing.Controller.addTopic(com.test.Testing.Student)

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 = []
Tests run: 2, Failures: 1, Errors: 0, Skipped: 0, Time elapsed: 1.809 sec <<< FAILURE! - in com.test.Testing.TestingApplicationTests
secondTest(com.test.Testing.TestingApplicationTests)  Time elapsed: 0.037 sec  <<< FAILURE!
java.lang.AssertionError: Status expected:<200> but was:<400>
Results :

Failed tests: 
  TestingApplicationTests.secondTest:97 Status expected:<200> but was:<400>
Plog
  • 9,164
  • 5
  • 41
  • 66
  • Request method change to post because in restController @RequestMapping(method= RequestMethod.POST,value="/students" ) you have then called it with post as well , aslike mvc.perform(post("/students")) .andExpect(status().isOk()) – MangduYogii Jun 07 '19 at 08:00

0 Answers0