2

我有以下控制器,我想对其进行 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());
4

1 回答 1

1

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

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

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

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

于 2014-05-16T13:31:54.943 回答