Java Reference
In-Depth Information
What if I want to check the results? In this case the result is random, but if my script has an
actual result based on input values, is there something that can be done then?
To handle this I'm going to need a binding for the script (again discussed in chapter 3 ) . A
binding is an object that allows input and output variables to be accessed from the script.
Script Binding
Any variable that isn't declared in a script is part of the binding and can be accessed from
outside.
Consider the classic “Hello, World!” script in Groovy. I'll put it in a package in the next
listing, but other than that it's the same script described in appendix B , “Groovy by fea-
ture.”
Listing 6.8. The “Hello, World!” script
package mjg
println 'Hello, World!'
This script doesn't contain any assert statements, but because it prints to the console I'd
like to be able to check the output. To do so I can assign the out property of the corres-
ponding binding to a StringBuffer , which I can access after the script executes. [ 7 ] The
following test has been added to the ScriptTests class started in listing 6.7 .
7 This isn't documented well at all, so consider it more value added for you by reading this topic. Guillaume Laforge
told me about it (and wrote it, too), so he gets the real credit.
Listing 6.9. A test that captures script output
@Test
void testHelloWorld() {
Binding binding = new Binding()
def content = new StringWriter()
binding.out = new PrintWriter(content)
GroovyShell shell = new GroovyShell(binding)
shell.evaluate(new File('src/main/groovy/mjg/hello_world.groovy'))
assert "Hello, World!" == content.toString().trim()
}
 
Search WWH ::




Custom Search