加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

Spring 3 MVC Controller集成测试 – 将Principal注入方法

发布时间:2020-12-15 01:23:40 所属栏目:大数据 来源:网络整理
导读:作为Spring 3 MVC的一部分,可以将当前登录的用户(Principle)对象注入控制器方法. 例如. @Controllerpublic class MyController { @RequestMapping(value="/update",method = RequestMethod.POST) public String update(ModelMap model,Principal principal)

作为Spring 3 MVC的一部分,可以将当前登录的用户(Principle)对象注入控制器方法.

例如.

@Controller
public class MyController {

    @RequestMapping(value="/update",method = RequestMethod.POST)
    public String update(ModelMap model,Principal principal) {

       String name = principal.getName();
       ... the rest here
    }
}

这是作为Spring 3文档的一部分记录的:
http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/mvc.html#mvc-ann-requestmapping-arguments.

这适用于生产代码.但是我不知道如何测试这个.
当我创建集成测试时(也设置了弹簧安全上下文)
并调用控制器句柄方法,然后Principal始终为null!

public class FareTypeControllerIntegrationTest extends SpringTestBase {

@Autowired
private MyController controller;

@Autowired
private AnnotationMethodHandlerAdapter handlerAdapter;

private final MockHttpServletRequest request = new MockHttpServletRequest();
private final MockHttpServletResponse response = new MockHttpServletResponse();

@Test
public void testUpdate() throws Exception {
    request.setRequestURI("/update");
    request.setMethod(HttpMethod.POST.name());
    ... setup rest of request

    ModelAndView mav = handlerAdapter.handle(request,response,controller);

    .. rest of assertions

}

测试正确运行,除Principal之外的所有内容都为null.

有任何想法吗?

TIA

阿尤布

最佳答案
快速浏览一下Spring源代码后,这应该可行:

request.setUserPrincipal(somePrincipal);

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读