且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

带有 JUnit 5 + Mockito 的 Spring 5 - 控制器方法返回 null

更新时间:2023-09-17 11:37:22

你可以直接调用控制器方法,就像我们对服务方法一样,但不建议这样做.使用 MockMvc,您可以检查 headerrequest param mapping 是否正确.另外,您还检查 端点映射 是否正确.另外Request METHOD也是正确的.如果您通过直接调用控制器方法来测试代码,所有这些都无法测试.

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.

您可以尝试的一件事是,不要在独立上下文中创建新对象,而是使用 Mock.即

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

在调用时,这样做

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

断言,你想要什么

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

您正在获取 null 或 400 或 404 http 状态?

You are getting null or 400 or 404 http status ?

如果你得到 400,那么请检查标题和请求.参数是否合适.如果您收到 404,请检查 URL 路径./loadData.ajax ,假设这是您在控制器方法中的请求映射路径.

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.