Groovy 如何断言两个闭包的相等性

Groovy 如何断言两个闭包的相等性,groovy,Groovy,在我的工作中,我有方法返回闭包作为标记生成器的输入。因此,出于测试目的,我们可以创建一个预期的闭包并断言预期的闭包等于一个方法返回的闭包吗?我尝试了以下代码,但断言失败 a = { foo { bar { input( type : 'int', name : 'dum', 'hello world' ) } } } b = { foo { bar { input( type

在我的工作中,我有方法返回闭包作为标记生成器的输入。因此,出于测试目的,我们可以创建一个预期的闭包并断言预期的闭包等于一个方法返回的闭包吗?我尝试了以下代码,但断言失败

a = {
    foo {
        bar {
            input( type : 'int', name : 'dum', 'hello world' )
        }
    }
}

b = {
    foo {
        bar {
            input( type : 'int', name : 'dum', 'hello world' )
        }
    }
}

assert a == b

我认为即使在调用闭包之后,也不可能断言闭包

//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)。这可以通过以下方式轻松完成(主要是)

@Grab('xmlunit:xmlunit:1.4')
导入groovy.xml.MarkupBuilder
导入org.custommonkey.xmlunit*
//测试用例中的存根XML
def预期值=新的StringWriter()
def mkp=新的MarkupBuilder(预期)
mkp.foo{
酒吧{
输入(类型:'int',名称:'dum','hello world')
}
}
/**不需要以下设置,因为应用程序将
*返回一个XML,如下所示。此处仅用于展示该功能。
* 
*   
*另一个你好世界
*   
* 
**/
def real=new StringWriter()
def mkp1=新的MarkupBuilder(真实)
mkp1.foo{
酒吧{
输入(类型:'float',名称:'dum','other hello world')
}
}
//使用XMLUnitAPI比较xmls
def xmlDiff=new Diff(预期为.toString(),实际为.toString())
断言!xmlDiff.idential()
断言!xmlDiff.similor()
上面看起来像是一个功能测试,但我会使用这个测试,除非有一个合适的单元测试来断言两个标记闭包

@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()