Java Reference
In-Depth Information
Running a script inside a test case is easy enough if no input or output variables are in-
volved. Because scripts normally contain assert statements that verify their correctness,
the key is simply to execute the script programmatically. That's what the GroovyShell
class is for.
Here's a simple example. Consider a short but powerful script that accesses the Internet
Chuck Norris Database, [ 6 ] reproduced from chapter 4 :
6 Arguably, this is why the internet was invented.
import groovy.json.JsonSlurper
def result = 'http://api.icndb.com/jokes/random'.toURL().text
def json = new JsonSlurper().parseText(result)
def joke = json?.value?.joke
assert joke
println joke
Chuck Norris can instantiate an interface
This script, when executed, accesses the RESTful web service at the URL shown, retrieves
a random joke in JavaScript Object Notation (JSON) form, parses (or, rather, slurps)
it, and prints the resulting joke. The script uses the safe dereference operator to avoid
NullPointerException s in case something goes wrong, but it has an assert
statement to check that something actually was retrieved. When executed, the result is
something like To test this script all I need to do is execute it and let the embedded as-
sert statement do the work. I can execute it programmatically as in the following listing.
Listing 6.7. A class to hold all the script tests
class ScriptTests {
@Test
void testChuckNorrisScript() {
GroovyShell shell = new GroovyShell()
shell.evaluate(new File('src/main/groovy/mjg/chuck_norris.groovy'))
}
}
The GroovyShell class, discussed in chapter 3 on Groovy and Java integration, has an
evaluate method that takes a File argument. I simply point the File to the script in
question, and the evaluate method on the shell executes it.
 
 
Search WWH ::




Custom Search