Java Reference
In-Depth Information
The out property of the binding is assigned to a PrintWriter wrapped around a
StringWriter , so that when the println method in the script is executed, the output
goes to the writer instead of the console. Then, after executing the script using the shell, I
can check that the proper statement was printed by accessing the writer and trimming its
output.
Normally a binding is used to pass input variables into a script. Here's a slight variation on
the previous example, using a name variable.
Listing 6.10. A script with a binding variable
package mjg
println "Hello, $name!"
Again, the only real difference here is that the print statement uses a name variable that
is not declared inside the script. That means it can be passed in from outside, as shown in
the following test.
Listing 6.11. Setting a binding variable to test a script
@Test
void testHelloName() {
Binding binding = new Binding()
binding.name = 'Dolly'
def content = new StringWriter()
binding.out = new PrintWriter(content)
GroovyShell shell = new GroovyShell(binding)
shell.evaluate(new File('src/main/groovy/mjg/hello_name.groovy'))
assert "Hello, Dolly!" == content.toString().trim()
}
The name variable is set to Dolly, and the result is confirmed as before.
6.2.1. Useful subclasses of GroovyTestCase: GroovyShellTestCase
The combination of script and binding is sufficiently common that the Groovy API now
includes the class groovy.util.GroovyShellTestCase . This is a subclass of
GroovyTestCase that instantiates a GroovyShell inside the setUp method. The
shell is provided as a protected attribute, but the class also includes a withBinding
method that takes a Map of parameters and a closure to execute. The following listing
shows tests for the Groovy scripts in this section.
Search WWH ::




Custom Search