Groovy的新手,并试图将常用代码提取到整齐的方法中。
我如何编写一个可以调用以进行断言的Groovy方法,并且可以在这两个非常相似的示例中使用:
boolean foundName = groups.any({ it.@'name' == expectedResult.name.toString()})
Assert.assertTrue(foundName, "name: ${expectedResult.name.toString()}")
... ...
boolean foundDisc = groups.any({ it.@'disc' == expectedResult.disc.toString()})
Assert.assertTrue(foundDisc, "disc: ${expectedResult.disc.toString()}")
我把它分成两行来表明我的意图。传递期望值很简单,但我如何通过另一个?在这些方面有签名的东西:
void assertAnyAttributeEquals(??? it ???, String attributeName, String expectedResult)
答案 0 :(得分:2)
A useful technique here is to use string interpolation as the attribute/field specifier. For example:
def myAssert = { groups, attr, expectedResult ->
def found = groups.any({ it.@"${attr}" == expectedResult."${attr}".toString() })
assert found
}
Here is a complete, working example:
class Result {
def name
def disc
}
def xmlStr = '''
<doc>
<groups name="hello" />
<groups disc="abc" />
</doc>
'''
def myAssert = { groups, attr, expectedResult ->
def found = groups.any({ it.@"${attr}" == expectedResult."${attr}".toString() })
assert found
}
def xml = new XmlSlurper().parseText(xmlStr)
myAssert(xml.groups, 'name', new Result('name': 'hello'))
myAssert(xml.groups, 'disc', new Result('disc': 'abc'))