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

Posted

技术标签:

【中文标题】Spring 3 MVC Controller 集成测试 - 将 Principal 注入方法【英文标题】:Spring 3 MVC Controller integration test - inject Principal into method 【发布时间】:2012-02-17 22:35:56 【问题描述】:

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

例如

@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.

这适用于生产代码。但是我不知道如何测试这个。 当我创建集成测试时(也设置了 spring 安全上下文) 并调用控制器句柄方法,则 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

阿尤布

【问题讨论】:

【参考方案1】:

在快速查看 Spring 源代码后,这应该可以工作:

request.setUserPrincipal(somePrincipal);

【讨论】:

【参考方案2】:

我前段时间尝试过,这是我用来设置身份验证的方法。

protected void setSecurityContext(String login)
            userDetailsTest = userManager.loadUserByUsername(login);
            TestingAuthenticationToken testingAuthenticationToken = new TestingAuthenticationToken(userDetailsTest, userDetailsTest.getAuthorities());
            SecurityContext securityContext = new SecurityContextImpl();
            securityContext.setAuthentication((Authentication) testingAuthenticationToken);
            SecurityContextHolder.setContext(securityContext);
          

然后我只是在测试的@Before 方法中调用它。 希望对您有所帮助。

【讨论】:

您好,上面的例子我试过了,和我之前试过的差不多。 糟糕,我的意思是我尝试了上述方法,但似乎没有用。谢谢【参考方案3】:

在使用 Spring Security 调用代码(例如您正在测试的 Principal 参数解析器)之前,我在测试中做了类似的事情:

SecurityContextHolder.getContext().setAuthentication(new UsernamePasswordAuthenticationToken("wiseau", "Love is blind"));

【讨论】:

以上是关于Spring 3 MVC Controller 集成测试 - 将 Principal 注入方法的主要内容,如果未能解决你的问题,请参考以下文章

Spring MVC框架 学习笔记总结

spring MVC注解深入研究

Spring mvc Controller接口

js怎么获取从springmvc后台传过来的数据

Spring MVC学习笔记——Controller

spring mvc controller实现原理