我正在尝试实现一个简单的 DSL 来安排事件。我必须在结束语中添加不带引号的“安排 session ”,并且它应该安排一次 session 。 “安排约会”将安排约会等。但是,我无法摆脱闭包中的引号,因为它将“ session ”注册为属性,并给我 groovy.lang.MissingPropertyException:没有这样的属性:类(class) session :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"
}
}
最佳答案
如果您将以下方法添加到 Scheduler
类中,您的测试就会通过:
def propertyMissing(String propertyName) {
propertyName
}
关于Groovy 删除字符串参数中的引号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69649126/