2011-03-10 58 views
4

我正在使用RestEasy開發REST服務器並使用模擬調度程序(org.jboss.resteasy.mockMockDispatcherFactory)在我的單元測試中測試服務。我的服務需要摘要式身份驗證,我會做出我的測試的一部分。在RestEasy中嘲笑摘要式身份驗證

我的每項服務均接受@Context SecurityContext securityContext參數。

有什麼辦法可以在調度程序中注入假的SecurityContext,這樣我就可以測試我的安全方法是否正常工作?

回答

2

您必須將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()); 
    } 
}