【问题标题】:Grails compiles but Groovy failsGrails 编译但 Groovy 失败
【发布时间】:2014-02-21 14:14:47
【问题描述】:

我在 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'
}
}

我可以知道为什么会有差异吗?谢谢。

【问题讨论】:

    标签: grails groovy


    【解决方案1】:

    在 Grails 中,Data binding 在您构造域类时生效。

    因此不会引发异常,但如果您在域实例上看到 errors 属性,您将在那里看到一些消息。

    afaik,如果域类在您的示例中没有定义属性(如“nameNot”),它将简单地忽略它。

    【讨论】:

    • 对,这是为了在控制器中支持 new User(params) 之类的东西,其中 params 映射将包含控制器和操作等属性,这些属性不能绑定到域类。
    猜你喜欢
    • 2020-12-29
    • 1970-01-01
    • 1970-01-01
    • 2021-10-07
    • 1970-01-01
    • 1970-01-01
    • 2011-03-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多