2013-08-21 25 views
1

在我的工作中,我有方法返回閉包作爲標記構建器的輸入。因此,出於測試的目的,我們是否可以進行預期的閉包並且聲稱預期的閉包與通過一種方法返回的相等?我嘗試了以下代碼,但聲明失敗。如何聲明兩次關閉的相等性

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

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

assert a == b 

回答

2

我認爲即使在打電話給他們後,斷言封閉也不可行。

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

上面看起來像一個功能測試,但我會用這個測試去除非另有有一個適當的單元測試爲發出兩個標記關閉。