
- •brief contents
- •contents
- •foreword
- •preface
- •acknowledgments
- •about this book
- •Roadmap
- •Code conventions and downloads
- •Author Online
- •About the author
- •about the cover illustration
- •1 Why add Groovy to Java?
- •1.1 Issues with Java
- •1.1.1 Is static typing a bug or a feature?
- •1.1.2 Methods must be in a class, even if you don’t need or want one
- •1.1.3 Java is overly verbose
- •1.1.4 Groovy makes testing Java much easier
- •1.1.5 Groovy tools simplify your build
- •1.2 Groovy features that help Java
- •1.3 Java use cases and how Groovy helps
- •1.3.1 Spring framework support for Groovy
- •1.3.2 Simplified database access
- •1.3.3 Building and accessing web services
- •1.3.4 Web application enhancements
- •1.4 Summary
- •2 Groovy by example
- •2.1 Hello, Groovy
- •2.2 Accessing Google Chart Tools
- •2.2.1 Assembling the URL with query string
- •2.2.2 Transmitting the URL
- •2.2.3 Creating a UI with SwingBuilder
- •2.3 Groovy Baseball
- •2.3.1 Database data and Plain Old Groovy Objects
- •2.3.2 Parsing XML
- •2.3.3 HTML builders and groovlets
- •2.4 Summary
- •3 Code-level integration
- •3.1 Integrating Java with other languages
- •3.2 Executing Groovy scripts from Java
- •3.2.1 Using JSR223 scripting for the Java Platform API
- •3.2.2 Working with the Groovy Eval class
- •3.2.3 Working with the GroovyShell class
- •3.2.4 Calling Groovy from Java the easy way
- •3.2.5 Calling Java from Groovy
- •3.3 Summary
- •4 Using Groovy features in Java
- •4.1 Treating POJOs like POGOs
- •4.2 Implementing operator overloading in Java
- •4.3 Making Java library classes better: the Groovy JDK
- •4.4 Cool AST transformations
- •4.4.1 Delegating to contained objects
- •4.4.2 Creating immutable objects
- •4.4.3 Creating singletons
- •4.5 Working with XML
- •4.6 Working with JSON data
- •4.7 Summary
- •5 Build processes
- •5.1 The build challenge
- •5.2 The Java approach, part 1: Ant
- •5.3 Making Ant Groovy
- •5.3.1 The <groovy> Ant task
- •5.3.2 The <groovyc> Ant task
- •5.3.3 Writing your build in Groovy with AntBuilder
- •5.3.4 Custom build scripts with Gant
- •5.3.5 Ant summary
- •5.4 The Java approach, part 2: Maven
- •5.4.2 The GMaven project
- •5.4.3 Maven summary
- •5.5 Grapes and @Grab
- •5.6 The Gradle build system
- •5.6.1 Basic Gradle builds
- •5.6.2 Interesting configurations
- •5.7 Summary
- •6 Testing Groovy and Java projects
- •6.1 Working with JUnit
- •6.1.1 A Java test for the Groovy implementation
- •6.1.2 A Groovy test for the Java implementation
- •6.1.3 A GroovyTestCase test for a Java implementation
- •6.2 Testing scripts written in Groovy
- •6.2.1 Useful subclasses of GroovyTestCase: GroovyShellTestCase
- •6.2.2 Useful subclasses of GroovyTestCase: GroovyLogTestCase
- •6.3 Testing classes in isolation
- •6.3.1 Coerced closures
- •6.3.2 The Expando class
- •6.3.3 StubFor and MockFor
- •6.4 The future of testing: Spock
- •6.4.1 The Search for Spock
- •6.4.2 Test well, and prosper
- •6.4.4 The trouble with tribbles
- •6.4.5 Other Spock capabilities
- •6.5 Summary
- •7 The Spring framework
- •7.1 A Spring application
- •7.2 Refreshable beans
- •7.3 Spring AOP with Groovy beans
- •7.4 Inline scripted beans
- •7.5 Groovy with JavaConfig
- •7.6 Building beans with the Grails BeanBuilder
- •7.7 Summary
- •8 Database access
- •8.1 The Java approach, part 1: JDBC
- •8.2 The Groovy approach, part 1: groovy.sql.Sql
- •8.3 The Java approach, part 2: Hibernate and JPA
- •8.4 The Groovy approach, part 2: Groovy and GORM
- •8.4.1 Groovy simplifications
- •8.5 Groovy and NoSQL databases
- •8.5.1 Populating Groovy vampires
- •8.5.2 Querying and mapping MongoDB data
- •8.6 Summary
- •9 RESTful web services
- •9.1 The REST architecture
- •9.3 Implementing JAX-RS with Groovy
- •9.4 RESTful Clients
- •9.5 Hypermedia
- •9.5.1 A simple example: Rotten Tomatoes
- •9.5.2 Adding transitional links
- •9.5.3 Adding structural links
- •9.5.4 Using a JsonBuilder to control the output
- •9.6 Other Groovy approaches
- •9.6.1 Groovlets
- •9.6.2 Ratpack
- •9.6.3 Grails and REST
- •9.7 Summary
- •10 Building and testing web applications
- •10.1 Groovy servlets and ServletCategory
- •10.2 Easy server-side development with groovlets
- •10.2.1 A “Hello, World!” groovlet
- •10.2.2 Implicit variables in groovlets
- •10.3.2 Integration testing with Gradle
- •10.3.3 Automating Jetty in the Gradle build
- •10.4 Grails: the Groovy “killer app”
- •10.4.1 The quest for the holy Grails
- •10.5 Summary
- •A.1 Installing a JDK
- •A.2 Installing Groovy
- •A.3 Testing your installation
- •A.4 IDE support
- •A.5 Installing other projects in the Groovy ecosystem
- •B.1 Scripts and the traditional example
- •B.2 Variables, numbers, and strings
- •B.2.1 Numbers
- •B.2.2 Strings and Groovy strings
- •B.3 Plain Old Groovy Objects
- •B.4 Collections
- •B.4.1 Ranges
- •B.4.2 Lists
- •B.4.3 Maps
- •B.5 Closures
- •B.6 Loops and conditionals
- •B.6.1 Loops
- •B.6.2 Conditionals
- •B.6.3 Elvis
- •B.6.4 Safe de-reference
- •B.7 File I/O
- •B.8.1 Parsing and slurping XML
- •B.8.2 Generating XML
- •B.8.3 Validation
- •B.9 JSON support
- •B.9.1 Slurping JSON
- •B.9.2 Building JSON
- •index
- •Symbols

Testing scripts written in Groovy |
137 |
(continued)
3Version 4 tests do not have a superclass. Instead, all of the assert methods are static methods in the org.junit.Assert class.
4By the Groovy truth, assert, assertTrue, and assertNotNull are all the same.
5Because the Groovy assert provides so much debugging information when it fails, it’s normally preferred over the standard JUnit assertEquals methods.
6GroovyTestCase extends TestCase from JUnit and adds a handful of convenience methods, like assertLength and shouldFail.
Testing a script written in Groovy involves special circumstances, especially if input data is supplied from outside. That’s the subject of the next section.
6.2Testing scripts written in Groovy
Testing scripts is a bit different from testing classes. You don’t normally instantiate a script and call a method on it, although you can. Instead, it’s easiest just to execute the script and let its own internal assert statements do any correctness checks.
USING ASSERT When Groovy developers write scripts, they typically add asserts to demonstrate that the script works properly.
Running a script inside a test case is easy enough if no input or output variables are involved. 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:
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
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 NullPointerExceptions 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
Chuck Norris can instantiate an interface
6 Arguably, this is why the internet was invented.
www.it-ebooks.info

138 |
CHAPTER 6 Testing Groovy and Java projects |
To test this script all I need to do is execute it and let the embedded assert 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.
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 Feature.”
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 corresponding 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.
Listing 6.9 A test that captures script output
@Test
void testHelloWorld() {
Binding binding = new Binding()
7This isn’t documented well at all, so consider it more value added for you by reading this book. Guillaume Laforge told me about it (and wrote it, too), so he gets the real credit.
www.it-ebooks.info

Testing scripts written in Groovy |
139 |
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()
}
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.1Useful 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.
www.it-ebooks.info

140 |
CHAPTER 6 Testing Groovy and Java projects |
|
|
|
|
|
Listing 6.12 Testing Groovy scripts using GroovyShellTestCase |
|
|
class ScriptShellTests extends GroovyShellTestCase { |
Executing a script, |
|
String base = 'src/main/groovy' |
which includes |
|
|
assert statements |
void testChuckNorris() {
shell.evaluate(new File("$base/mjg/chuck_norris.groovy"))
}
void testHelloWorld() {
def content = new StringWriter()
withBinding([out:new PrintWriter(content)]) { shell.evaluate(new File("$base/mjg/hello_world.groovy")) assert "Hello, World!" == content.toString().trim()
}
}
void testHelloName() {
def content = new StringWriter()
withBinding([out:new PrintWriter(content), name:'Dolly']) { shell.evaluate(new File("$base/mjg/hello_name.groovy")) assert "Hello, Dolly!" == content.toString().trim()
}
}
}
The first test finds the script to run and executes it using the shell instantiated in the superclass. The other tests use the withBinding method to override the out variable and provide an input parameter. The results are the same as instantiating the GroovyShell and Binding classes directly.
The previous example showed how to capture standard output from a script, but normally scripts return concrete values. The withBinding method returns whatever the script returns. As a trivial example, consider the following powerful Groovy calculator, saved in a file called calc.groovy:
z = x + y
Because none of the three variables (x, y, and z) are declared, they can all be accessed through the script’s binding. The next listing shows a test for this script that validates the returned value.
Listing 6.13 A test for the addition script, calc.groovy
void testAddition() {
def result = withBinding( [x:3,y:4] ) {
shell.evaluate(new File('src/main/groovy/mjg/calc.groovy')) shell.context.z
}
assert 7 == result
}
The last line of the closure accesses the z variable, whose value is retrieved from the binding.
www.it-ebooks.info