2014-02-21 41 views
1

我在Groovy的控制檯測試了以下的代碼和按預期都失敗:第一測試 :Grails的編譯,但Groovy的失敗

class TekEvent { 
    Date organizer 
} 

    def tekEvent = new TekEvent(organizer: 'John Doe') 
    assert tekEvent.organizer == 'John Doe' 

    Exception thrown 
    org.codehaus.groovy.runtime.typehandling.GroovyCastException: Cannot cast object 'John Doe' with class 'java.lang.String' to class 'java.util.Date' 

第二個測試:

class DifferentTekEvent { 
    String name 
} 

def tekEvent = new TekEvent(nameNot: 'John Doe') 
assert tekEvent.nameNot == 'John Doe' 
Exception thrown 

groovy.lang.MissingPropertyException: No such property: nameNot for class: DifferentTekEvent 

的等同物被運行在Grails中(即類被實例化並用於單元測試),但不會引發異常。例如:

@TestFor(TekEvent) 
class TekEventSpec extends Specification { 

void "test"() { 

    def tekEvent = new TekEvent(organizer: 'aasdf') //no expceptions thrown here. Why? 
    expect: 
     tekEvent.organizer == 'aasdf' 
} 
} 

我可以知道爲什麼會有差異?謝謝。

回答

2

在Grails中,構建域類時Data binding會生效。

因此不會拋出異常,但是如果您在域實例上看到errors屬性,那麼您將在其中看到一些消息。

afaik,如果域類沒有定義屬性(如'nameNot')在你的例子中,它將簡單地忽略它。

+2

對,這是爲了在控制器中支持'new User(params)'等東西,其中'params'映射將包含控制器和動作等屬性,而這些屬性不能綁定到域類。 –