0

I have following method in my Spring application

public static String getCurrentUserStudentId() {
    return ((LdapPerson) SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getID();
}

This works on the application run, but when I run a test calling this method, it gives

org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken cannot be cast to fi.utu.security.ldap.userdetails.LdapPerson

I'm not that familiar with Spring Security to give all the files this could be related, but ask me. I hope someone can tell what to do with this.

Cœur
  • 37,241
  • 25
  • 195
  • 267
mjgirl
  • 1,214
  • 7
  • 24
  • 42

1 Answers1

0

SecurityContextHolder keeps a reference to a "strategy" in a static variable which means that this detail leaks from test to test.

You have several options:

  1. In your test, set the correct strategy using one of the setters of SecurityContextHolder

  2. Create a mock implementation for getCurrentUserStudentId which returns a fixed result for the test.

  3. Put the code to get the current user id into a bean and inject that instead of calling SecurityContextHolder. Implement two versions of this bean: One which calls SecurityContextHolder and another which returns a string.

Aaron Digulla
  • 321,842
  • 108
  • 597
  • 820
  • I think it would be nice to keep modifications inside test classes only. Can you give me an code example of setting the strategy on test? I'm not sure what you mean by that. – mjgirl Aug 21 '13 at 11:52
  • Look through the code for calls to `setContext()` and `setStrategyName()` – Aaron Digulla Aug 21 '13 at 11:57