I tried to test the extjs application, and after successfully installing testAuthenticationToken, it suddenly stopped working for no apparent reason.
I could not get the above answers to work, so my solution was to skip this spring bit in a test environment. I introduced a seam around spring as follows:
public class SpringUserAccessor implements UserAccessor { @Override public User getUser() { SecurityContext context = SecurityContextHolder.getContext(); Authentication authentication = context.getAuthentication(); return (User) authentication.getPrincipal(); } }
User is a custom type.
Then I wrap it in a class that has only an option for test code to switch spring.
public class CurrentUserAccessor { private static UserAccessor _accessor; public CurrentUserAccessor() { _accessor = new SpringUserAccessor(); } public User getUser() { return _accessor.getUser(); } public static void UseTestingAccessor(User user) { _accessor = new TestUserAccessor(user); } }
The test version is as follows:
public class TestUserAccessor implements UserAccessor { private static User _user; public TestUserAccessor(User user) { _user = user; } @Override public User getUser() { return _user; } }
In the calling code, I still use the correct user loaded from the database:
User user = (User) _userService.loadUserByUsername(username); CurrentUserAccessor.UseTestingAccessor(user);
Obviously, this is not suitable if you really need to use security, but I run the installation without protection to deploy testing. I thought someone else would face a similar situation. This is the pattern I used to mock static dependencies. Another alternative is that you can keep the wrapper class static, but I prefer this because the code dependencies are more explicit, since you need to pass CurrentUserAccessor to the classes where it is needed.
Jonny Leeds Jun 19 '14 at 11:17 2014-06-19 11:17
source share