如何断言两个闭包相等 [英] How to assert equality of two closures

查看:111
本文介绍了如何断言两个闭包相等的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的工作中,我有一些方法可以返回闭包作为标记构建器的输入.因此,出于测试目的,我们是否可以进行期望的关闭并断言期望的关闭等于一个方法返回的关闭?我尝试了以下代码,但是断言失败了.

In my work, I have methods to return closures as inputs for markup builders. So, for testing purposes, can we make an expected closure and assert the expected one equal to the one returned by one method? I tried the following code, but the assert failed.

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

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

assert a == b

推荐答案

我认为断言闭包(即使在调用它们之后)也不可行.

I do not think it will be feasible to assert the closures even after calling them.

//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()的错误,因为闭包不代表配置脚本(因为它是标记)

Using ConfigSlurper will give the error about input() since the closure does not represent a config script (because it is a Markup)

可以断言该行为的一种方法是断言有效负载(因为您已经提到了MarkupBuilder).可以通过如下方式使用 XmlUnit 轻松完成此操作(主要是

One way you can assert the behavior is by asserting the payload (since you have mentioned MarkupBuilder). That can be easily done by using XmlUnit as below(mainly 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()

上面看起来像是一个功能测试,但除非有适当的单元测试来断言两个标记闭包,否则我将继续进行此测试.

Above looks like a functional test, but I would go with this test unless otherwise there is an appropriate unit test to assert two markup closures.

这篇关于如何断言两个闭包相等的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆