SlideShare a Scribd company logo
Java Testing on the Fast Lane
Be more effective while
   programming tests
(and have some fun too!)

          Goal
About the presenter




• Java Developer since the beginning
• Open Source believer since 1997
• Groovy development team member since 2007
• Griffon project co-founder
Agenda
•What is Groovy
•Groovy + Testing Frameworks
•How Groovy helps
•Mocking with Groovy
•XML Processing
•Functional UI Testing
•Resources
What is Groovy?

• Groovy is an agile and dynamic language for the
    Java Virtual Machine
•   Builds upon the strengths of Java but has
    additional power features inspired by languages
    like Python, Ruby & Smalltalk
•   Makes modern programming features available to
    Java developers with almost-zero learning
    curve
•   Supports Domain Specific Languages and
    other compact syntax so your code becomes easy
    to read and maintain
What is Groovy?

• Increases developer productivity by reducing
    scaffolding code when developing web, GUI,
    database or console applications
•   Simplifies testing by supporting unit testing
    and mocking out-of-the-box
•   Seamlessly integrates with all existing Java
    objects and libraries
•   Compiles straight to Java byte code so you can
    use it anywhere you can use Java
HelloWorld.java

public class HelloWorld {
   String name;

    public void setName(String name)
    { this.name = name; }
    public String getName(){ return name; }

    public String greet()
    { return “Hello “+ name; }

    public static void main(String args[]){
       HelloWorld helloWorld = new HelloWorld();
       helloWorld.setName(“Groovy”);
       System.err.println( helloWorld.greet() );
    }
}
HelloWorld.groovy

public class HelloWorld {
   String name;

    public void setName(String name)
    { this.name = name; }
    public String getName(){ return name; }

    public String greet()
    { return “Hello “+ name; }

    public static void main(String args[]){
       HelloWorld helloWorld = new HelloWorld();
       helloWorld.setName(“Groovy”);
       System.err.println( helloWorld.greet() );
    }
}
Equivalent HelloWorld 100% Groovy

class HelloWorld {
   String name
   def greet() { "Hello $name" }
}

def helloWorld = new HelloWorld(name:"Groovy")
println helloWorld.greet()
1st Mantra
          Java is Groovy, Groovy is Java

•Every single Java class is a Groovy class, the
 inverse is also true. This means your Java can call
 my Groovy in vice versa, without any clutter nor
 artificial bridge.
•Groovy has the same memory and security models
 as Java.
•Almost 98% Java code is Groovy code, meaning you
 can in most cases rename *.java to *.groovy and it
 will work.
Common Gotchas
• Java Array initializers are not supported, but lists
  can be coerced into arrays.

• Inner class definitions are not supported (coming
  in Groovy 1.7).
2nd Mantra
      Groovy is Java and Groovy is not Java

•Flat learning curve for Java developers, start with
 straight Java syntax then move on to a groovier
 syntax as you feel comfortable.
•Groovy delivers closures, meta-programming, new
 operators, operator overloading, enhanced POJOs,
 properties, native syntax for Maps and Lists, regular
 expressions, enhanced class casting, optional
 typing, and more!
Groovy + Testing Frameworks

• Any Groovy script may become a testcase
  • assert keyword enabled by default

• Groovy provides a GroovyTestCase base class
  • Easier to test exception throwing code

• Junit 4.x and TestNG ready, Groovy supports
  JDK5+ features
  • Annotations
  • Static imports
  • Enums
How Groovy helps

• Write less with optional keywords – public, return,
  arg types & return types

• Terser syntax for property access
• Native syntax for Lists and Maps
• Closures
• AST Transformations – compile time meta-
  programming
Accessing Properties
// Java
public class Bean {
  private String name;
  public void setName(String n) { name = n; }
  public String getName() { return name; }
}

// Groovy
Bean bean = new Bean(name: “Duke”)
assert bean.name == “Duke”
bean.name = “Tux”
assert bean.name == “Tux”
assert bean.name == bean.getName()
Native Syntax for Maps and Lists
Map map = [:]
assert map instanceof java.util.Map
map["key1"] = "value1"
map.key2 = "value2"
assert map.size() == 2
assert map.key1 == "value1"
assert map["key2"] == "value2"

List list = []
assert list instanceof java.util.List
list.add("One")
list << "Two"
assert list.size() == 2
assert ["One","Two"] == list
Closures (1)
int count = 0
def closure = {->
  0.upto(10) { count += it }
}
closure()
assert count == (10*11)/2

def runnable = closure as Runnable
assert runnable instanceof java.lang.Runnable
count = 0
runnable.run()
assert count == (10*11)/2
Closure (2)
// a closure with 3 arguments, third one has
// a default value
def getSlope = { x, y, b = 0 ->
   println "x:${x} y:${y} b:${b}"
   (y - b) / x
}

assert 1 == getSlope( 2, 2 )
def getSlopeX = getSlope.curry(5)
assert 1 == getSlopeX(5)
assert 0 == getSlopeX(2.5,2.5)
// prints
// x:2 y:2 b:0
// x:5 y:5 b:0
// x:5 y:2.5 b:2.5
AST Transformations
import java.text.SimpleDateFormat
class Event {
    @Delegate Date when
    String title, url
}
def df = new SimpleDateFormat("MM/dd/yyyy")
def oscon = new Event(title: "OSCON 09",
   url: "http://en.oreilly.com/oscon2009/",
   when: df.parse("07/20/2009"))
def so2gx = new Event(title: "SpringOne2GX",
   url: "http://www.springone2gx.com/",
   when: df.parse("10/19/2009"))

assert oscon.before(so2gx.when)
AST Transformations

• @Singleton
• @Lazy
• @Delegate
• @Immutable
• @Bindable
• @Newify
• @Category/@Mixin
• @PackageScope
But how do I run Groovy tests?

• Pick your favourite IDE!
   • IDEA
   • Eclipse
   • NetBeans
• Command line tools
   • Ant
   • Gant
   • Maven
   • Gradle
   • Good ol’ Groovy shell/console
Testing exceptions in Java

public class JavaExceptionTestCase extends TestCase {
   public void testExceptionThrowingCode() {
        try {
           new MyService().doSomething();
           fail("MyService.doSomething has been implemented");
        }catch( UnsupportedOperationException expected ){
           // everything is ok if we reach this block
        }
    }
}
Testing exceptions in Groovy

class GroovyExceptionTestCase extends GroovyTestCase {
   void testExceptionThrowingCode() {
      shouldFail( UnsupportedOperationException ){
         new MyService().doSomething()
      }
   }
}
Mocking with Groovy

• Known (Java) mocking libraries
  • EasyMock – record/replay
  • Jmock – write expectations as you go
  • Mockito – the new kid on the block

• Use dynamic proxies as stubs

• Use StubFor/MockFor
  • inspired by EasyMock
  • no external libraries required (other than Groovy)
Dynamic Proxies
Oscon Java Testing on the Fast Lane
StubFor/MockFor
• caller – collaborator
• mocks/stubs define expectations on collaborators
• mocks are strict, expectation must be fulfilled both
    in order of invocation and cardinality.
•   stubs are loose, expectations must fulfil cardinality
    but may be invoked in any order.
•   CAVEAT: can be used to mock both Groovy and
    Java collaborators, caller must be Groovy though.
Groovy Mocks
Oscon Java Testing on the Fast Lane
XML Processing: testing databases

• DbUnit: a Junit extension for testing databases

• Several options at your disposal
  • Old school – extend DatabaseTestCase
  • Flexible – use an IDataBaseTester implementation
  • Roll your own Database testcase
Inline XML dataset
import org.dbunit.*
import org.junit.*

class MyDBTestCase {
   IDatabaseTester db

    @BeforeClass void init(){
       db = new JdbcDatabaseTester("org.hsqldb.jdbcDriver",
              "jdbc:hsqldb:sample", "sa", "" )
       // insert table schema
       def dataset = """
       <dataset>
           <company name="Acme"/>
           <employee name="Duke" company_id="1">
       </dataset>
       """
       db.dataset = new FlatXmlDataSet( new StringReader(dataset) )
       db.onSetUp()
    }

    @AfterClass void exit() { db.onTearDown() }
}
Compile-checked dataset
import org.dbunit.*
import org.junit.*
Import groovy.xml.MarkupBuilder

class MyDBTestCase {
   IDatabaseTester db

    @BeforeClass void init(){
       db = new JdbcDatabaseTester("org.hsqldb.jdbcDriver",
             "jdbc:hsqldb:sample", "sa", "" )
       // insert table schema
       def dataset = new MarkupBuilder().dataset {
          company( name: Acme )
          employee( name: "Duke", company_id: 1 )
       }
       db.dataset = new FlatXmlDataSet( new StringReader(dataset) )
       db.onSetUp()
    }

    @AfterClass void exit() { db.onTearDown() }
}
Functional UI Testing

• These tests usually require more setup
• Non-developers usually like to drive these tests
• Developers usually don’t like to code these tests
• No Functional Testing => unhappy customer =>
  unhappy developer
Groovy to the rescue!

• Web:
  • Canoo WebTest - leverages AntBuilder
  • Tellurium - a Groovier Selenium

• Desktop:
  • FEST – next generation Swing testing

• BDD:
  • Easyb
  • Spock
FEST + Easyb
Resources
http://groovy.codehaus.org

http://junit.org
http://testng.org
http://www.dbunit.org
http://easyb.org
http://easytesting.org

http://groovy.dzone.come
http://jroller.com/aalmiray
twitter: @aalmiray
Q&A
Thank You!
Credits
http://www.flickr.com/photos/patrick_pjm/3323599305/
http://www.flickr.com/photos/guitrento/2564986045/
http://www.flickr.com/photos/wainwright/1050237241/
http://www.flickr.com/photos/lancecatedral/3046310713/
http://www.flickr.com/photos/fadderuri/841064754/
http://www.flickr.com/photos/17258892@N05/2588347668/
http://www.flickr.com/photos/chelseaaaaaa/3564365301/
http://www.flickr.com/photos/psd/2086641/

More Related Content

What's hot (20)

PDF
Better DSL Support for Groovy-Eclipse
Andrew Eisenberg
 
PDF
JVM for Dummies - OSCON 2011
Charles Nutter
 
PDF
Down the Rabbit Hole
Charles Nutter
 
ODP
Getting started with Clojure
John Stevenson
 
PDF
Atlassian Groovy Plugins
Paul King
 
KEY
JavaOne 2011 - JVM Bytecode for Dummies
Charles Nutter
 
PDF
Down the Rabbit Hole: An Adventure in JVM Wonderland
Charles Nutter
 
KEY
Øredev 2011 - JVM JIT for Dummies (What the JVM Does With Your Bytecode When ...
Charles Nutter
 
PDF
Exploring Clojurescript
Luke Donnet
 
PPTX
Kotlin is charming; The reasons Java engineers should start Kotlin.
JustSystems Corporation
 
PDF
Spock: Test Well and Prosper
Ken Kousen
 
PDF
Java libraries you can't afford to miss
Andres Almiray
 
PDF
Infinum android talks_10_getting groovy on android
Infinum
 
KEY
Groovy DSLs (JavaOne Presentation)
Jim Driscoll
 
PDF
Gradle in a Polyglot World
Schalk CronjĂŠ
 
PDF
Webinar: MongoDB Persistence with Java and Morphia
MongoDB
 
PDF
Flutter 是什麼?用 Flutter 會省到時間嗎? @ GDG Devfest2020
Johnny Sung
 
PDF
Everything you wanted to know about Stack Traces and Heap Dumps
Andrei Pangin
 
KEY
JavaOne 2012 - JVM JIT for Dummies
Charles Nutter
 
PDF
Fun with Functional Programming in Clojure
Codemotion
 
Better DSL Support for Groovy-Eclipse
Andrew Eisenberg
 
JVM for Dummies - OSCON 2011
Charles Nutter
 
Down the Rabbit Hole
Charles Nutter
 
Getting started with Clojure
John Stevenson
 
Atlassian Groovy Plugins
Paul King
 
JavaOne 2011 - JVM Bytecode for Dummies
Charles Nutter
 
Down the Rabbit Hole: An Adventure in JVM Wonderland
Charles Nutter
 
Øredev 2011 - JVM JIT for Dummies (What the JVM Does With Your Bytecode When ...
Charles Nutter
 
Exploring Clojurescript
Luke Donnet
 
Kotlin is charming; The reasons Java engineers should start Kotlin.
JustSystems Corporation
 
Spock: Test Well and Prosper
Ken Kousen
 
Java libraries you can't afford to miss
Andres Almiray
 
Infinum android talks_10_getting groovy on android
Infinum
 
Groovy DSLs (JavaOne Presentation)
Jim Driscoll
 
Gradle in a Polyglot World
Schalk CronjĂŠ
 
Webinar: MongoDB Persistence with Java and Morphia
MongoDB
 
Flutter 是什麼?用 Flutter 會省到時間嗎? @ GDG Devfest2020
Johnny Sung
 
Everything you wanted to know about Stack Traces and Heap Dumps
Andrei Pangin
 
JavaOne 2012 - JVM JIT for Dummies
Charles Nutter
 
Fun with Functional Programming in Clojure
Codemotion
 

Similar to Oscon Java Testing on the Fast Lane (20)

PPT
GTAC Boosting your Testing Productivity with Groovy
Andres Almiray
 
PPT
Svcc Groovy Testing
Andres Almiray
 
PPT
Boosting Your Testing Productivity with Groovy
James Williams
 
PPT
Javaone2008 Bof 5101 Groovytesting
Andres Almiray
 
PDF
Apache Groovy: the language and the ecosystem
Kostas Saidis
 
PDF
Groovy On Trading Desk (2010)
Jonathan Felch
 
PDF
Groovy.pptx
Giancarlo Frison
 
PPT
Groovy presentation
Manav Prasad
 
PDF
Cool Jvm Tools to Help you Test - Aylesbury Testers Version
Schalk CronjĂŠ
 
PDF
An Introduction to Groovy for Java Developers
Kostas Saidis
 
PDF
Using the Groovy Ecosystem for Rapid JVM Development
Schalk CronjĂŠ
 
PDF
Learning groovy -EU workshop
adam1davis
 
PDF
Cool JVM Tools to Help You Test
Schalk CronjĂŠ
 
PDF
Introduction to Oracle Groovy
Deepak Bhagat
 
PDF
OpenLogic
webuploader
 
PPTX
Groovy Programming Language
Aniruddha Chakrabarti
 
PDF
The Future of JVM Languages
VictorSzoltysek
 
PDF
Introduction to Groovy (Serbian Developer Conference 2013)
Joachim Baumann
 
PDF
Groovy and Grails talk
desistartups
 
GTAC Boosting your Testing Productivity with Groovy
Andres Almiray
 
Svcc Groovy Testing
Andres Almiray
 
Boosting Your Testing Productivity with Groovy
James Williams
 
Javaone2008 Bof 5101 Groovytesting
Andres Almiray
 
Apache Groovy: the language and the ecosystem
Kostas Saidis
 
Groovy On Trading Desk (2010)
Jonathan Felch
 
Groovy.pptx
Giancarlo Frison
 
Groovy presentation
Manav Prasad
 
Cool Jvm Tools to Help you Test - Aylesbury Testers Version
Schalk CronjĂŠ
 
An Introduction to Groovy for Java Developers
Kostas Saidis
 
Using the Groovy Ecosystem for Rapid JVM Development
Schalk CronjĂŠ
 
Learning groovy -EU workshop
adam1davis
 
Cool JVM Tools to Help You Test
Schalk CronjĂŠ
 
Introduction to Oracle Groovy
Deepak Bhagat
 
OpenLogic
webuploader
 
Groovy Programming Language
Aniruddha Chakrabarti
 
The Future of JVM Languages
VictorSzoltysek
 
Introduction to Groovy (Serbian Developer Conference 2013)
Joachim Baumann
 
Groovy and Grails talk
desistartups
 
Ad

More from Andres Almiray (20)

PDF
Dealing with JSON in the relational world
Andres Almiray
 
PDF
Deploying to production with confidence 🚀
Andres Almiray
 
PDF
Going beyond ORMs with JSON Relational Duality Views
Andres Almiray
 
PDF
Setting up data driven tests with Java tools
Andres Almiray
 
PDF
Creando, creciendo, y manteniendo una comunidad de codigo abierto
Andres Almiray
 
PDF
Liberando a produccion con confianza
Andres Almiray
 
PDF
Liberando a produccion con confidencia
Andres Almiray
 
PDF
OracleDB Ecosystem for Java Developers
Andres Almiray
 
PDF
Softcon.ph - Maven Puzzlers
Andres Almiray
 
PDF
Maven Puzzlers
Andres Almiray
 
PDF
Oracle Database Ecosystem for Java Developers
Andres Almiray
 
PDF
JReleaser - Releasing at the speed of light
Andres Almiray
 
PDF
Building modular applications with the Java Platform Module System and Layrry
Andres Almiray
 
PDF
Going Reactive with g rpc
Andres Almiray
 
PDF
Building modular applications with JPMS and Layrry
Andres Almiray
 
PDF
Taking Micronaut out for a spin
Andres Almiray
 
PDF
Apache Groovy's Metaprogramming Options and You
Andres Almiray
 
PDF
What I wish I knew about Maven years ago
Andres Almiray
 
PDF
What I wish I knew about maven years ago
Andres Almiray
 
PDF
The impact of sci fi in tech
Andres Almiray
 
Dealing with JSON in the relational world
Andres Almiray
 
Deploying to production with confidence 🚀
Andres Almiray
 
Going beyond ORMs with JSON Relational Duality Views
Andres Almiray
 
Setting up data driven tests with Java tools
Andres Almiray
 
Creando, creciendo, y manteniendo una comunidad de codigo abierto
Andres Almiray
 
Liberando a produccion con confianza
Andres Almiray
 
Liberando a produccion con confidencia
Andres Almiray
 
OracleDB Ecosystem for Java Developers
Andres Almiray
 
Softcon.ph - Maven Puzzlers
Andres Almiray
 
Maven Puzzlers
Andres Almiray
 
Oracle Database Ecosystem for Java Developers
Andres Almiray
 
JReleaser - Releasing at the speed of light
Andres Almiray
 
Building modular applications with the Java Platform Module System and Layrry
Andres Almiray
 
Going Reactive with g rpc
Andres Almiray
 
Building modular applications with JPMS and Layrry
Andres Almiray
 
Taking Micronaut out for a spin
Andres Almiray
 
Apache Groovy's Metaprogramming Options and You
Andres Almiray
 
What I wish I knew about Maven years ago
Andres Almiray
 
What I wish I knew about maven years ago
Andres Almiray
 
The impact of sci fi in tech
Andres Almiray
 
Ad

Recently uploaded (20)

PDF
Reverse Engineering of Security Products: Developing an Advanced Microsoft De...
nwbxhhcyjv
 
PDF
Python basic programing language for automation
DanialHabibi2
 
PPTX
Q2 FY26 Tableau User Group Leader Quarterly Call
lward7
 
PDF
Presentation - Vibe Coding The Future of Tech
yanuarsinggih1
 
PPTX
"Autonomy of LLM Agents: Current State and Future Prospects", Oles` Petriv
Fwdays
 
PDF
DevBcn - Building 10x Organizations Using Modern Productivity Metrics
Justin Reock
 
PDF
CIFDAQ Market Insights for July 7th 2025
CIFDAQ
 
PDF
July Patch Tuesday
Ivanti
 
PDF
"Beyond English: Navigating the Challenges of Building a Ukrainian-language R...
Fwdays
 
PDF
Log-Based Anomaly Detection: Enhancing System Reliability with Machine Learning
Mohammed BEKKOUCHE
 
PPTX
Top iOS App Development Company in the USA for Innovative Apps
SynapseIndia
 
PPTX
OpenID AuthZEN - Analyst Briefing July 2025
David Brossard
 
PDF
HCIP-Data Center Facility Deployment V2.0 Training Material (Without Remarks ...
mcastillo49
 
PDF
Smart Trailers 2025 Update with History and Overview
Paul Menig
 
PDF
SFWelly Summer 25 Release Highlights July 2025
Anna Loughnan Colquhoun
 
PDF
HubSpot Main Hub: A Unified Growth Platform
Jaswinder Singh
 
PDF
Newgen Beyond Frankenstein_Build vs Buy_Digital_version.pdf
darshakparmar
 
PDF
CIFDAQ Weekly Market Wrap for 11th July 2025
CIFDAQ
 
PDF
Timothy Rottach - Ramp up on AI Use Cases, from Vector Search to AI Agents wi...
AWS Chicago
 
PDF
How Startups Are Growing Faster with App Developers in Australia.pdf
India App Developer
 
Reverse Engineering of Security Products: Developing an Advanced Microsoft De...
nwbxhhcyjv
 
Python basic programing language for automation
DanialHabibi2
 
Q2 FY26 Tableau User Group Leader Quarterly Call
lward7
 
Presentation - Vibe Coding The Future of Tech
yanuarsinggih1
 
"Autonomy of LLM Agents: Current State and Future Prospects", Oles` Petriv
Fwdays
 
DevBcn - Building 10x Organizations Using Modern Productivity Metrics
Justin Reock
 
CIFDAQ Market Insights for July 7th 2025
CIFDAQ
 
July Patch Tuesday
Ivanti
 
"Beyond English: Navigating the Challenges of Building a Ukrainian-language R...
Fwdays
 
Log-Based Anomaly Detection: Enhancing System Reliability with Machine Learning
Mohammed BEKKOUCHE
 
Top iOS App Development Company in the USA for Innovative Apps
SynapseIndia
 
OpenID AuthZEN - Analyst Briefing July 2025
David Brossard
 
HCIP-Data Center Facility Deployment V2.0 Training Material (Without Remarks ...
mcastillo49
 
Smart Trailers 2025 Update with History and Overview
Paul Menig
 
SFWelly Summer 25 Release Highlights July 2025
Anna Loughnan Colquhoun
 
HubSpot Main Hub: A Unified Growth Platform
Jaswinder Singh
 
Newgen Beyond Frankenstein_Build vs Buy_Digital_version.pdf
darshakparmar
 
CIFDAQ Weekly Market Wrap for 11th July 2025
CIFDAQ
 
Timothy Rottach - Ramp up on AI Use Cases, from Vector Search to AI Agents wi...
AWS Chicago
 
How Startups Are Growing Faster with App Developers in Australia.pdf
India App Developer
 

Oscon Java Testing on the Fast Lane