4

我正在使用 RestEasy 开发 REST 服务器,并使用模拟调度程序 ( org.jboss.resteasy.mockMockDispatcherFactory) 在我的单元测试中测试服务。我的服务需要摘要式身份验证,我将把这部分作为我的测试。

我的每个服务都接受一个@Context SecurityContext securityContext参数。

有什么办法可以SecurityContext在调度程序中注入一个假的,以便我可以测试我的安全方法是否正常运行?

4

2 回答 2

3

您必须将 . 添加SecurityContext到上下文数据映射中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());
    }
}
于 2012-07-07T15:11:32.033 回答
0

对于今天遇到这个问题的人,添加上下文已从RestEasyProviderFactory类移到Dispatcher使用getDefaultContextObjects()方法的类中。

我用新电话编辑了旧答案:

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());
        dispatcher.getDefaultContextObjects().put(SecurityContext.class, new FakeSecurityContext());

        MockHttpRequest request = MockHttpRequest.get("/");
        MockHttpResponse response = new MockHttpResponse();

        dispatcher.invoke(request, response);

        assertEquals("unit-test-scheme", response.getContentAsString());
    }
}
于 2020-10-01T09:49:42.163 回答