unit-testingmockingresteasydigest-authentication

Mocking digest authentication in RestEasy


I am using RestEasy to develop a REST server and using the mock dispatcher (org.jboss.resteasy.mockMockDispatcherFactory) for testing the service in my unit tests. My service requires digest authentication and I would to make that part of my testing.

Each of my services accepts a @Context SecurityContext securityContext parameter.

Is there any way is inject a fake SecurityContext in the dispatcher so that I can test that my security methods function properly?


Solution

  • You have to add the SecurityContext into the context data map in ResteasyProviderFactory.

    public class SecurityContextTest  {
    
        @Path("/")
        public static class Service {
            @Context
            SecurityContext context;
    
            @GET
            public String get(){
                return context.getAuthenticationScheme();
            }
        }
    
        public static class FakeSecurityContext extends ServletSecurityContext {
    
            public FakeSecurityContext() {
                super(null);
            }
    
            @Override
            public String getAuthenticationScheme() {
                return "unit-test-scheme";
            }
        }
    
        @Test
        public void securityContextTest() throws Exception {
            Dispatcher dispatcher = MockDispatcherFactory.createDispatcher();
            dispatcher.getRegistry().addSingletonResource(new Service());
            ResteasyProviderFactory.getContextDataMap().put(SecurityContext.class, new FakeSecurityContext());
    
            MockHttpRequest request = MockHttpRequest.get("/");
            MockHttpResponse response = new MockHttpResponse();
    
            dispatcher.invoke(request, response);
    
            assertEquals("unit-test-scheme", response.getContentAsString());
        }
    }