【发布时间】:2011-12-17 22:05:25
【问题描述】:
我正在尝试对我的 Spring 应用程序进行单元测试。 使用 Spring-Security,我很难模拟 SecurityContext 以便对我的控制器进行单元测试。
我发现了以下问题:Unit testing with Spring Security
我正在尝试让“社区维基”答案(此时为第二个答案)在我的网络应用程序上运行。
我主要使用注释驱动的开发,然后我有以下内容:
MainController.java
@Controller
public class MainController {
private User currentUser;
@Autowired
@Scope(value = "request", proxyMode = ScopedProxyMode.TARGET_CLASS)
public void setCurrentUser(User currentUser) {
this.currentUser = currentUser;
}
...
}
UserFactory.java
@Component
public class UserFactory {
@Bean
public User getUserDetails() {
Authentication a = SecurityContextHolder.getContext().getAuthentication();
if (a == null) {
return null;
} else {
return (User) a.getPrincipal();
}
}
}
用户.java
public class User implements UserDetails {
private long userId;
private String username;
private String password;
private boolean enabled;
private ArrayList<GrantedAuthority> authorities;
public User() {
}
...
}
问题是 getUserDetails() 方法似乎从未被调用过,并且 UserFactory 从未使用过。 (我尝试了 System.out.println 并尝试了调试器)
但是没有关于 MainController 在运行时或在任何请求时未连接的错误。
属性 currentUser 似乎总是为空。
我也查看了这个问题,但没有找到满足我需求的东西:problem in Spring session scope bean with AOP
这是我的第一个 Spring web-app,请不要苛刻。 :)
【问题讨论】:
标签: java spring spring-mvc spring-security