【问题标题】:How to assert equality of two closures如何断言两个闭包相等
【发布时间】:2013-08-21 00:29:41
【问题描述】:

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

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

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

assert a == b

【问题讨论】:

    标签: groovy


    【解决方案1】:

    我认为即使在调用闭包之后断言它们也是不可行的。

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

    上面看起来像一个功能测试,但我会使用这个测试,除非有适当的单元测试来断言两个标记闭包。

    【讨论】:

      猜你喜欢
      • 2010-09-29
      • 2017-11-07
      • 1970-01-01
      • 1970-01-01
      • 2014-06-26
      • 1970-01-01
      • 2020-01-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多