2011-04-06 70 views
2

我即將開發帶有Web服務的Web應用程序。我已經調整了jax-ws和ws-security。我用的soapUI並送到下一個請求:如何測試ws-security?

<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:soap="..." > 
<soapenv:Header> 
    <wsse:Security xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd" soapenv:mustUnderstand="1"> 
    <wsu:Timestamp xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd" wsu:Id="Timestamp-2"> 
     <wsu:Created>2011-11-11T00:05:05.044Z</wsu:Created> 
     <wsu:Expires>2012-11-11T00:10:05.044Z</wsu:Expires> 
    </wsu:Timestamp> 
    <wsse:UsernameToken xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd" wsu:Id="UsernameToken-1"> 
     <wsse:Username>user</wsse:Username> 
     <wsse:Password>password</wsse:Password> 
    </wsse:UsernameToken> 
    </wsse:Security> 
</soapenv:Header> 
    <soapenv:Body> 
     <soap:foo> 
     <arg0>1</arg0> 
     </soap:foo> 
    </soapenv:Body> 
</soapenv:Envelope> 

我需要從頭部得到用戶名和密碼。在應用程序,我可以通過下面的代碼獲得它:

@Resource 
WebServiceContext context; 
... 
private static final String PRINCIPAL_RESULT = "wss4j.principal.result"; 
... 
WSUsernameTokenPrincipal wsutp = (WSUsernameTokenPrincipal) context.getMessageContext().get(PRINCIPAL_RESULT);  
.. 
String user = wsutp.getName() 
String password = wsutp.getPassword(); 

但我不知道我應該怎麼用JUnit測試進行測試,因爲context.getMessageContext()將在測試類NULL

有沒有人知道一個很好的指南或提供代碼示例?

回答

1

您需要模擬junit測試中不可用的資源。請看一下像Mokito這樣的框架(http://mockito.org/)。你可以做s.th.像:

//You can mock concrete classes, not only interfaces 
    LinkedList mockedList = mock(LinkedList.class); 

//stubbing 
when(mockedList.get(0)).thenReturn("first"); 
when(mockedList.get(1)).thenThrow(new RuntimeException()); 

或者爲你的情況:

WSUsernameTokenPrincipal mockedWsutp = mock(WSUsernameTokenPrincipal.class); 
when(mockedWsutp.getName()).thenReturn("TheNameRequiredForYourTestCase"); 
... 

有了這些框架,你可以模擬不可用的資源。他們很容易與junit整合。我希望這提供了一些有用的想法。