首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在spring-mvc-test中传入参数?

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

Stack Overflow用户
提问于 2016-11-21 01:43:02
回答 1查看 416关注 0票数 0

我必须对此进行测试;

代码语言:javascript
复制
/** 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;
}

我的测试是这样的;

代码语言:javascript
复制
@Test
public void getProfileBalance() throws Exception {
    this.mockMvc.perform(get("/profile/balance")
            .andExpect(status().isOk())
            .andExpect(view().name("balance"));
} 

我真的不明白我怎么能传入这个主体实例。我该怎么做呢?

EN

回答 1

Stack Overflow用户

发布于 2016-11-21 01:52:25

最简单的方法就是做

代码语言:javascript
复制
@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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/40707237

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档