SoapUI:如何将 0 转换为 'false'

SoapUI: How to cast 0 as 'false'

我正在使用 SoapUI 测试 WCF 服务。我有一个 XPath 匹配断言,其中 Declare 是:

if (boolean(//a:IsClick/text()[1])) then //a:IsClick else ''

对于源XML,节点是

<a:IsClick>false</a:IsClick>

所以声明部分等同于 'false'。

预期的盒子有这个:

${#ResponseAsXml#(//CLICK[text()],'')}

并且 XML(来自 JDBC 测试步骤)是:

<CLICK>0</CLICK>

所以期望值为0。

我需要让这两个相等,这样我的断言才会通过。一种方法是将预期结果从 0 转换为 'false'。我怎样才能做到这一点?或者有更好的方法吗?

最简单的解决方案是将其变成一个 Groovy 问题 - 一个 Groovy 断言。

这是一个可视化(参见 documentation):

def negIsClick = "false"
def negCLICK = "0"

def posIsClick = "true"
def posCLICK = "1"

// fake "cast" the text to boolean
assert !(negIsClick.equals("true") ?: false)
assert (posIsClick.equals("true") ?: false)

assert !negCLICK.toInteger()   // zero is false
assert posCLICK.toInteger()    // all other numbers are true

// note the exclamations everywhere
assert !(negIsClick.equals("true") ?: false) == !negCLICK.toInteger()
assert !(posIsClick.equals("true") ?: false) == !posCLICK.toInteger()
// this fails
assert (negIsClick.equals("true") ?: false) == negCLICK.toInteger()

最后一个失败了,因为您不能将布尔值与整数进行比较。但在此之前的情况下,! 首先将所有内容转换为布尔值。

因此,在您的情况下,您需要执行以下操作:

// read in the two values
def IsClick = context.expand( '${XML test step#Response//*:IsClick}' )
def CLICK = context.expand( '${JDBC test step#ResponseAsXml//*:CLICK}' )
// now compare them
assert !(IsClick.equals("true") ?: false) == !CLICK.toInteger()

在 XPath 中,boolean() 函数 returns 数字、字符串或节点集的布尔值。在您想要将数字转换为布尔值的情况下,boolean(0) returns false,其余数字 boolean(n) returns true。另一方面 boolean() of string returns false for boolean('false') or for boolean('') (empty string) for the rest of strings boolean() returns true .所以你的问题是,使用 text() 你得到的 '0' 作为字符串而不是数字,所以当你尝试转换 boolean('0') 时,你会得到 true.

在你的情况下,如果你的 JDBC Test Step 有一些 XML 结果,例如:

<Results>
    <CLICK>0</CLICK>
</Results>

您可以将此 0 转换为 false,将 boolean() 添加到您的表达式中,并使用 number() 函数代替 text()。所以要将 0 转换为 false 使用:

${#ResponseAsXml#(boolean(//CLICK[number()]))}

而不是:

${#ResponseAsXml#(//CLICK[text()],'')}

希望这对您有所帮助,

assert  '1'.toInteger().asBoolean()
assert !'0'.toInteger().asBoolean()