【问题标题】:Groovy Removing Quotes in String ParametersGroovy 删除字符串参数中的引号
【发布时间】:2021-10-20 15:43:47
【问题描述】:

我正在尝试实现一个简单的 DSL 来安排事件。我将不得不在结尾加上不带引号的“安排会议”,它应该安排一次会议。 “安排约会”将安排约会等。但是,我无法摆脱关闭中的引号,因为它将“会议”注册为属性,并给了我groovy.lang.MissingPropertyException: No such property: meeting for class: groovy.SchedulerTest

我知道我们可以在 Kotlin 中用“中缀”标记函数,但不确定如何在 Groovy 中模拟它。

这是 DSL 的类:

class Scheduler {
  //var meeting = "meeting" //I could uncomment this and it would work, but then I would need to create a new variable for every type of meeting
  String type

  def static create(closure) {
    Scheduler scheduler = new Scheduler()
    closure.delegate = scheduler
    closure()
    return scheduler.print_values()
  }

  def schedule(String type) {
    this.type = type
  }
  
  def print_values() {
    return "${this.type} scheduled"
  }
}

这是我试图通过的测试用例:

class SchedulerTest extends Specification {

  def "Scheduler Type Test"() {
    setup:
    String type_test = Scheduler.create {
      schedule meeting //it runs just fine if I write -> schedule "meeting". But I am not allowed to use any quotes as my requirements.
    }

    expect:
      type_test == "meeting scheduled"
  }

}

【问题讨论】:

    标签: groovy dsl gradle-kotlin-dsl


    【解决方案1】:

    如果您将以下方法添加到 Scheduler 类,您的测试将通过:

    def propertyMissing(String propertyName) {
        propertyName
    }
    

    【讨论】:

    • 要求不明确,但如果你只想支持特定的属性名称,当然可以在propertyMissing中添加一些逻辑,在某些情况下返回propertyName,并在下面抛出MissingPropertyException其他人,那会奏效。另一种方法是在Scheduler 中定义您想要支持的特定属性并为其分配值,例如String meeting = 'meeting',在这种情况下您不需要propertyMissing
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-09-14
    • 1970-01-01
    • 2014-02-16
    • 2017-04-18
    • 1970-01-01
    • 1970-01-01
    • 2017-09-24
    相关资源
    最近更新 更多