QuickTime and a
TIFF (Uncompressed) decompressor
are needed to see this picture.
Unit Testing Java using
Groovy and Mock Objects
Walker Hale
Human Genome Sequencing Center
Baylor College of Medicine
The Plan
Groovy makes testing Java better.
Motivation
Introduce Groovy
Apply Groovy to Testing
Mock Objects
TestNG
Grand Demo
The Setting
Java shop
Subversion for version control
Maven 2 for most builds
Groovy for various tasks
Many apps running against a common
database and set of libraries
An Ideal Deliverable in Our Shop
Code checked into version control
Builds with maven 2
Passes all unit tests
$ svn checkout \
$repo/my-project/trunk \
my-project
$ cd my-project
$ mvn test
The Plot
The Motivation
More unit testing!
The Insight
Small changes in the difficulty or unpleasantness
of a task produce disproportionately large changes
in how much that task is performed.
Enter Groovy
Groovy in 15 Minutes
Almost all Java code is Groovy code
no inner classes
[Link]
Groovy adds:
Fun syntactic sugar
Lazy method dispatch
Methods to the standard Java library classes
Closures
Groovy-specific classes
Interactive shell
Syntax Sugar
// [Link]
import [Link].*;
public class MapSample {
public static void main(String[] args) {
Map<Object, Object> m =
new LinkedHashMap<Object, Object>();
[Link]("red" , 1);
[Link]("blue", 2);
[Link]([Link]());
[Link](m);
}
}
// [Link]
def m = [red:1, blue:2]
println [Link]()
println m // .toString() for Java-style output
Syntax Sugar
$ javac [Link]
$ java MapSample
class [Link]
{red=1, blue=2}
$ groovy [Link]
class [Link]
["red":1, "blue":2]
$ groovyc [Link]
$ java -cp `pwd`:$GROOVY_EMBED_JAR MapSampleG
class [Link]
["red":1, "blue":2]
Lazy Dispatch & Expanding JDK
// [Link]
def x = "Hello World"
def l = ["abc", "def"]
println [Link]()
[Link] [Link]().toList()
println l
l << "more" << "stuff"
println l
$ groovy [Link]
{"Hello", "World"}
["abc", "def", "Hello", "World"]
["abc", "def", "Hello", "World", "more", "stuff"]
Closures 1
// [Link]
def c = { it + it }
println c(2)
println c("hello ")
def foo(Closure cl) {
cl(5, 7)
}
println foo { x, y -> x + y }
println foo { x, y -> x * y }
$ groovy [Link]
4
hello hello
12
35
Closures 2
// [Link]
[2, 3, 5].each {
println it * it
}
[red:1, blue:2].each { key, value ->
println key * value
}
$ groovy [Link]
4
9
25
red
blueblue
Closures 3
// [Link]
def strategies = [ add:{ a,b -> a + b },
mult:{ a,b -> a * b } ]
[[1,2], [3,4], [5,6]].each { data ->
[Link] { name, code ->
printf "%d %4s %2d\n", data,
name, code(data)
}
}
$ groovy [Link]
[1, 2] add 3
[1, 2] mult 2
[3, 4] add 7
[3, 4] mult 12
[5, 6] add 11
[5, 6] mult 30
Testing in Groovy
Compiled (not limited) with JUnit 3.8.2
Adds
GroovyTestCase
New assertions, such as shouldFail
GroovyTestSuite
Simple command line operation
URLs
[Link]
[Link]
Demo Time!
Resources
[Link]
Documentation
Differences+from+Java
Testing+Guide
[Link]