带有 JUnit 5 + Mockito 的 Spring 5 - 控制器方法返回 null [英] Spring 5 with JUnit 5 + Mockito - Controller method returns null

查看:50
本文介绍了带有 JUnit 5 + Mockito 的 Spring 5 - 控制器方法返回 null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试测试在 MainController 中定义的名为 loadData 的方法,该方法以字符串形式返回结果.尽管此方法实际上在 Web 应用程序在 servlet 容器上运行时(或在我调试代码时)返回数据,但当我从基于 JUnit 5 的测试类调用它时没有数据返回Mockito.

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 when the web app runs on servlet container (or when I debug the code), no data returns when I invoke it from a test class based on JUnit 5 with Mockito.

这是我的配置:

@ContextConfiguration(classes = {WebAppInitializer.class, AppConfig.class, WebConfig.class})
@Transactional
@WebAppConfiguration
public class TestMainController {

    @InjectMocks
    private MainController mainController;

    private MockMvc mockMvc;

    @BeforeEach
    public void init() {
        mockMvc = MockMvcBuilders.standaloneSetup(this.mainController).build();
    }

    @Test
    public void testLoadData() throws Exception {
        MvcResult mvcResult = mockMvc
                .perform(MockMvcRequestBuilders.get("/loadData.ajax"))
                .andExpect(MockMvcResultMatchers.status().isOk()).andReturn();

        Assertions.assertNotNull(mvcResult.getResponse().getContentAsString(), "response should not be null");
    }

}

由于 java.lang.NullPointerException 测试失败,因为 this.mainControllernull.

The test fails due to java.lang.NullPointerException as the this.mainController is null.

环境详情:

Spring version: 5.0.3
JUnit version: 5.0.3
mockito version: 1.9.5
hamcrest version: 1.3
json-path-assert version: 2.2.0

这里是MainControllerloadData方法:

@RequestMapping(value = "/loadData.ajax", method = RequestMethod.GET)
public String loadData(HttpServletRequest request, HttpServletResponse response) {
    List list = mainService.loadData(); // starts a transaction and invokes the loadData method of mainDAO repository which basically loads data from the database
    return JSONArray.fromObject(list).toString();
}

推荐答案

你可以直接调用控制器方法,就像我们对服务方法一样,但不建议这样做.使用 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.

这篇关于带有 JUnit 5 + Mockito 的 Spring 5 - 控制器方法返回 null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆