Spring 5 with JUnit 5 + Mockito - Controller method returns null

后端 未结 1 1262
醉酒成梦
醉酒成梦 2021-01-15 07:04

I try to test a method named as loadData defined in MainController which returns result as a string. Despite that this method actually returns data

相关标签:
1条回答
  • 2021-01-15 07:39

    You can call controller method directly, just like we do for service method, but this is not recommended. Using MockMvc, you check for header and request param mapping are proper. Plus, you also check for end point mapping is correct. Plus the Request METHOD is also correct. All these you cannot test if you test your code by directly calling the controller method.

    One thing you can try is, instead of creating new object inside the standalone context, use the Mock. i.e

    mockMvc = MockMvcBuilders.standaloneSetup(this. mainController).build();
    

    And while calling, do this

    MvcResult mvcResult = mockMvc
        .perform(MockMvcRequestBuilders.get("/loadData.ajax"))
        .andExpect(MockMvcResultMatchers.status().isOk()).andReturn();
    

    Assert , what you would like to

    Assert.assertEquals("response does not match", mvcResult.getResponse().getContentAsString(),
        "some expected response");
    

    You are getting null or 400 or 404 http status ?

    If you are getting 400, then please check the header and req. param if any are proper. If you are getting 404 then please check the URL path. /loadData.ajax , assuming this is your request mapping path in controller method.

    0 讨论(0)
提交回复
热议问题