我认为即使在调用它们之后断言闭包也是不可行的。
//Since you have Markup elements in closure
//it would not even execute the below assertion.
//Would fail with error on foo()
assert a() != b()
使用 ConfigSlurper 将给出错误,input()
因为闭包不代表配置脚本(因为它是标记)
断言行为的一种方法是断言有效负载(因为您提到了 MarkupBuilder)。这可以通过使用如下XmlUnit轻松完成(主要是Diff)。
@Grab('xmlunit:xmlunit:1.4')
import groovy.xml.MarkupBuilder
import org.custommonkey.xmlunit.*
//Stub out XML in test case
def expected = new StringWriter()
def mkp = new MarkupBuilder(expected)
mkp.foo {
bar {
input( type : 'int', name : 'dum', 'hello world' )
}
}
/**The below setup will not be required because the application will
* be returning an XML as below. Used here only to showcase the feature.
* <foo>
* <bar>
* <input type='float' name='dum'>Another hello world</input>
* </bar>
* </foo>
**/
def real = new StringWriter()
def mkp1 = new MarkupBuilder(real)
mkp1.foo {
bar {
input( type : 'float', name : 'dum', 'Another hello world' )
}
}
//Use XmlUnit API to compare xmls
def xmlDiff = new Diff(expected.toString(), real.toString())
assert !xmlDiff.identical()
assert !xmlDiff.similar()
上面看起来像一个功能测试,但除非有适当的单元测试来断言两个标记闭包,否则我会使用这个测试。