Results 1 to 4 of 4

Thread: mocking in junit

  1. #1

    Default 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 at 12:33 AM. Reason: added commet at end

  2. #2
    Join Date
    Jun 2006
    Location
    The Netherlands
    Posts
    13,624

    Default

    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.
    Marten Deinum
    Java Consultant / Pragmatist / Open Source Enthousiast / Author


    Pro Spring MVC: With Web Flow
    Conspect

    Have you read the reference guide.
    Use the [ code ] tags, young padawan

  3. #3

    Default 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);

  4. #4
    Luke Taylor is offline Senior Member Acegi Security System TeamSpring Team
    Join Date
    Aug 2004
    Location
    Glasgow, Scotland
    Posts
    3,449

    Default

    getUsername() is part of the UserDetails interface, so it has to be in all the implementations...
    Spring - by Pivotal
    twitter @tekul

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •