如何测试ws-security?

时间:2011-04-06 08:11:45

标签: java unit-testing cxf ws-security

我即将使用Web服务开发Web应用程序。我已经调整了jax-ws和ws-security。我使用了soapUI并发送了下一个请求:

<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

有谁知道一个好的指南或提供代码示例?

2 个答案:

答案 0 :(得分: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集成。我希望这提供了一些有用的想法。

答案 1 :(得分:0)

试试这个: 使用XWS-Security(纯文本密码)保护JAX-WS Web服务 [http://mananvpanchal.blogspot.com/2010/06/jax-ws-webservice-with-plaintext.html][1]