4

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. :)

Community
  • 1
  • 1
Timothée Jeannin
  • 9,652
  • 2
  • 56
  • 65

1 Answers1

4

The first thing I noticed is that you've put @Scope in the wrong place. It should go on the @Bean method, not the @Autowired method, i.e.

@Autowired
public void setCurrentUser(User currentUser) {

@Bean
@Scope(value = "request", proxyMode = ScopedProxyMode.TARGET_CLASS)
public User getUserDetails() {

I'm surprised that Spring didn't complain about that.

skaffman
  • 398,947
  • 96
  • 818
  • 769