Chapter 7
[ 143 ]
static String sentMessage
static def sendMessage1(id, message) {
sentMessage = "Sending (${message}) to ${id}"
}
given:
sendMessage1 "GroovyDSL", "Hi from GeeTwitter"
expect: "message sent correctly"
sentMessage == "Sending (Hi from GeeTwitter) to GroovyDSL"
when:
sendMessage1 "Hi from GeeTwitter", "GroovyDSL"
then: "message sent incorrectly"
! (sentMessage == "Sending (Hi from GeeTwitter) to GroovyDSL")
The second invocation here would, of course, cause an exception in the real
GeeTwitter as we try to send a message to a user called "Hi from GeeTwitter"
instead of to GroovyDSL. A small change removes this ambiguity and improves the
readability of the DSL:
static def sendMessage2(Map params, message) {
sentMessage = "Sending (${message}) to ${params.to}"
}
when:
sendMessage2 to: "GroovyDSL", "Hi from GeeTwitter"
then: "message sent correctly"
sentMessage == "Sending (Hi from GeeTwitter) to GroovyDSL"
when:
sendMessage2 "Hi from GeeTwitter", to: "GroovyDSL"
then: "message sent incorrectly"
sentMessage == "Sending (Hi from GeeTwitter) to GroovyDSL"
It might seem a little redundant or inefficient, from a programming point of view, to
package a single value in a map. However, even though we are only going to pass
the single value to a parameter along with a message parameter, naming this to
parameter adds significantly to the resulting DSL script in terms of legibility.