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

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

问题描述

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

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

推荐答案

您可以直接调用控制器方法,就像我们对service方法所做的那样,但是不建议这样做.使用MockMvc,您检查标题请求参数映射是否正确.另外,您还要检查端点映射是否正确.另外,请求方法也是正确的.如果您通过直接调用controller方法来测试代码,则无法测试所有这些.

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,请检查网址路径. /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天全站免登陆