SoapUI在模拟服务脚本中获取请求参数

时间:2009-06-03 15:27:32

标签: xml web-services groovy soapui

对于所有SoapUI常客来说,这可能是一个非常简单的方法。

在SoapUI模拟服务响应脚本中,如何在我回复的请求中提取值?

假设传入的请求有

<ns1:foo>
  <ns3:data>
    <ns3:CustomerNumber>1234</ns3:CustomerNumber>
  </ns3:data>
</ns1:foo>

如何将“1234”变为Groovy变量?我尝试使用xmlHolder,但我似乎有错误的XPath。

(我知道如何设置属性并将其值集成到响应中。)

4 个答案:

答案 0 :(得分:32)

如果您想访问SOAP请求并进行一些XPath处理,那么凭借GPathXmlSlurper的强大功能,可以更轻松地在soapUI中执行此操作。

以下是您访问客户编号的方式:

def req = new XmlSlurper().parseText(mockRequest.requestContent)
log.info "Customer #${req.foo.data.CustomerNumber}"

从Groovy 1.6.3(在soapUI 2.5及更高版本中使用)开始,默认情况下,XmlSlurper在名称空间感知和非验证模式下运行,因此您无需执行任何其他操作。

干杯!
Shonzilla

答案 1 :(得分:24)

又一个例子:

def request = new XmlSlurper().parseText(mockRequest.requestContent)
def a = request.Body.Add.x.toDouble()
def b = request.Body.Add.y.toDouble()
context.result = a + b

在这个例子中,我们从请求中获取两个参数并将它们转换为双精度数。这样我们就可以对参数进行计算。此示例的示例SoapUI响应是:

<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:typ="http://example.org/math/types/">
   <soapenv:Header/>
   <soapenv:Body>
      <typ:AddResponse>
         <result>${result}</result>
      </typ:AddResponse>
   </soapenv:Body>
</soapenv:Envelope>

您可以看到计算结果如何传递回响应。

答案 2 :(得分:0)

在纯Java(不使用SoapUI)中,您只需创建一个自定义命名上下文,如下所示:

import java.util.Iterator;
import java.util.List;

import javax.xml.XMLConstants;
import javax.xml.namespace.NamespaceContext;

class WSNamespaceContext implements NamespaceContext
{
    public String getNamespaceURI(String prefix)
    {
        if ( prefix.equals("ns3") )
            return "http://www.mysite.com/services/taxservice";
       else if (prefix.equals("soapenv"))
            return "http://schemas.xmlsoap.org/soap/envelope/";
        else
            return XMLConstants.NULL_NS_URI;
    }

    public String getPrefix(String namespace)
    {
        if ( namespace.equals("http://www.mysite.com/services/taxservice") )
            return "ns3";
        else if (namespace.equals("http://schemas.xmlsoap.org/soap/envelope/"))
            return "soapenv";
        else
            return null;
    }

    public Iterator<List<String>> getPrefixes(String namespace)
    {
        return null;
    }
}

然后,解析它:

XPathFactory factory = XPathFactory.newInstance(); 
XPath xp = factory.newXPath(); 
xp.setNamespaceContext( nsc ); 
XPathExpression xpexpr = xp.compile("//ns3:CustomerNumber/text()");
NodeList nodes = (NodeList)xpexpr.evaluate(doc, XPathConstants.NODESET); 
for ( int i = 0; i < nodes.getLength(); i++ )  { 
    String val = nodes.item(i).getNodeValue();
    System.out.println( "Value: " + val  ); 
}

答案 3 :(得分:0)

扩展http://www.soapui.org/soap-mocking/creating-dynamic-mockservices.html并基于http://www.soapui.org/apidocs/com/eviware/soapui/support/xmlholder.html我提出了这个问题:

<?php
if (!empty($_GET)) {
    $SQL = "INSERT INTO bom (finish_product) VALUES ('".$_GET['finish_product:']."')";
    $result = mysql_query($SQL);
    echo 1;
} else {
    echo -1;
}
?>