在Spring MVC Test期间获得错误"预期状态:< 200>但是:< 400>"?

时间:2018-01-19 11:04:10

标签: spring-mvc spring-boot spring-boot-test spring-mvc-test

请帮我解决错误。 我想使用MockMvc测试我的Rest控制器,但在测试后我得到了上述错误。

我的GetTest成功运行,但我的POST测试丢失了错误。也许我编写POST MVC测试的方式不正确。以下是整个代码,如果需要任何其他信息,请发表评论。

@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);
        }

}

单元测试类:

@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测试成功完成(即获取),但我的第二次测试(即POST)失败并出现以下错误:

以下是日志。

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()

或者可能需要添加/启用类型信息?)

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>

0 个答案:

没有答案