Announcement Announcement Module
Collapse
No announcement yet.
mocking in junit Page Title Module
Move Remove Collapse
This topic is closed
X
X
Conversation Detail Module
Collapse
  • Filter
  • Time
  • Show
Clear All
new posts

  • mocking in junit

    how do i mock this?

    Code:
    public static UserDetails getUserFromSecurityContext() {
            return (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
    }
    i thought it would but it doesn't

    Code:
    GrantedAuthority[] ga = new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ADS_ADMIN")};
    TestingAuthenticationToken token = new TestingAuthenticationToken("admin", "password", ga);
    token.setAuthenticated(true);        
    SecurityContextHolder.getContext().setAuthentication(token);
    i'm doing auth'ing against an ldap server.

    having a chapter in the docs on testing would be nice.


    thx
    Last edited by denov; May 22nd, 2009, 12:33 AM. Reason: added commet at end

  • #2
    Hmm that should basically work, although you might want to pass a valid UserDetails object instead of "admin".

    Giving a bit more information might also be helpful.

    Comment


    • #3
      got it

      after a couple hours of reading java docs and playing around i figured it out. i need to user an LdapUserDetail since my code that testing calls getUsername() which isn't in all the other implementations of UserDetails.

      Code:
              
      LdapUserDetailsImpl.Essence ud = new LdapUserDetailsImpl.Essence();
      ud.setDn("admin");
      ud.setUsername("admin");
      ud.setPassword("password");
      ud.setAuthorities(new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ADS_ADMIN")});
      TestingAuthenticationToken token = new TestingAuthenticationToken(ud.createUserDetails(),"password");
      token.setAuthenticated(true);
      SecurityContextHolder.getContext().setAuthentication(token);

      Comment


      • #4
        getUsername() is part of the UserDetails interface, so it has to be in all the implementations...

        Comment

        Working...
        X