PDA

View Full Version : How to mock acegi context for controller unit test


davidallen39
May 7th, 2008, 07:49 AM
Hi All,
I have a controller class that calls the following method.

SecurityContextHolder.getContext().getAuthenticati on();

I then extract the principal and pass that to a service. My problem is that I am trying to mock the service while performing a unit test for the controller.

Is it possible to set the Authentication object in the security context holder object in the unit test?

I am sure it is but not sure of the code. A small sample would be great

simongroenewolt
May 11th, 2008, 08:10 AM
You can create set your authentication object like this:


SecurityContext context = new SecurityContextImpl();
context.setAuthentication(authentication);
SecurityContextHolder.setContext(context);


The authentication object has to implement the spring security Authentication interface, most of the time I'm using a PrincipalSpringSecurityUserToken myself.