【问题标题】:Spring Junit Controller Mock Not WorkingSpring Junit 控制器模拟不工作
【发布时间】:2014-07-04 23:03:53
【问题描述】:

我有以下控制器,我想对其进行 Junit 测试,

@RequestMapping(value = "/path", method = RequestMethod.Get)
public String getMyPath(HttpServletRequest request, Model model) {

    Principal principal = request.getUserPrincipal();
    if (principal != null) {
        model.addAttribute("username", principal.getName());
    }
    return "view";
}

JUnit 方法如下所示:

@Test
public void testGetMyPath() throws Exception {

    when(principalMock.getName()).thenReturn("someName");

    this.mockMvc.perform(get("/path")).andExpect(status().isOk());
}

principalMock 是这样声明的:

@Mock
private Principal principalMock;

问题是我在主体上调用 getName() 方法时在这一行得到 NullPointerException。

model.addAttribute("username", principal.getName());

【问题讨论】:

  • 为什么在请求映射为 GET 时在测试中发布?
  • 我编辑了问题,

标签: spring spring-mvc controller mocking spring-mvc-test


【解决方案1】:

您对 Principal 的模拟完全没有效果,因为它无法在任何地方发挥作用(控制器没有使用任何注入的依赖项来生成主体,但它使用了 HttpServletRequest)。

您需要将测试更改为以下内容:

this.mockMvc.perform(get("/path").principal(principalMock)).andExpect(status().isOk());

这会起作用,因为模拟主体将被传递给 MockHttpServletRequest,而 MockHttpServletRequest 实际上将被传递给控制器​​方法

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-06-29
    • 1970-01-01
    • 2015-02-13
    • 1970-01-01
    • 2016-06-02
    • 2020-09-27
    • 2018-03-09
    • 2021-06-12
    相关资源
    最近更新 更多