I'm trying to unit-test my Spring application. Using Spring-Security, i have troubles to mock the SecurityContext in order to unit-test my controllers.
I found the following question : Unit testing with Spring Security
And i'm trying to have the "community-wiki" answer (2nd answer at this time) working on my web-app.
I mostly use annotation-driven developpement then i have the following :
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();
}
}
}
User.java
public class User implements UserDetails {
private long userId;
private String username;
private String password;
private boolean enabled;
private ArrayList<GrantedAuthority> authorities;
public User() {
}
...
}
The problem is that the method getUserDetails() seem to be never called and the UserFactory never used. ( I tried System.out.println and i tried the debugger)
But there is no error about the MainController not being wired at runtime or at any request.
The attribute currentUser seems to be alaways null.
I also looked over this question without finding something that meets my needs : problem in Spring session scope bean with AOP
It is my first Spring web-app, please don't be harsh. :)