如何在spring-mvc-test中传入参数?

时间:2016-11-20 17:43:02

标签: java spring spring-mvc spring-mvc-test

我必须测试一下;

/** Displays the balance us page. */
@RequestMapping(value = "/profile/balance")
public ModelAndView balance(Principal principal) {
    ModelAndView model = new ModelAndView("balance");
    String username = principal.getName();
    User user = userService.findUserByUsername(username);

    model.addObject("moneyEarned", user.getMoneyEarned());
    model.addObject("moneySpent", user.getMoneySpent());

    return model;
}

我的测试看起来像那样;

@Test
public void getProfileBalance() throws Exception {
    this.mockMvc.perform(get("/profile/balance")
            .andExpect(status().isOk())
            .andExpect(view().name("balance"));
} 

我真的不明白我如何传递该Principal实例。 我怎么能这样做?

1 个答案:

答案 0 :(得分:0)

最简单的方法是做

@Test
public void getProfileBalance() throws Exception {
    SecurityContext ctx = new SecurityContextImpl();
    ctx.setAuthentication(new UsernamePasswordAuthenticationToken("principal", "password"));
    SecurityContextHolder.setStrategyName(SecurityContextHolder.MODE_GLOBAL);
    SecurityContextHolder.setContext(ctx);
    this.mockMvc.perform(get("/profile/balance")
            .andExpect(status().isOk())
            .andExpect(view().name("balance"));
    SecurityContextHolder.clearContext();
} 

或者您可以使用Spring Security Test library