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
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
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

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

What's hot (20)

Better DSL Support for Groovy-Eclipse
Better DSL Support for Groovy-EclipseBetter DSL Support for Groovy-Eclipse
Better DSL Support for Groovy-Eclipse
 
JVM for Dummies - OSCON 2011
JVM for Dummies - OSCON 2011JVM for Dummies - OSCON 2011
JVM for Dummies - OSCON 2011
 
Down the Rabbit Hole
Down the Rabbit HoleDown the Rabbit Hole
Down the Rabbit Hole
 
Getting started with Clojure
Getting started with ClojureGetting started with Clojure
Getting started with Clojure
 
Atlassian Groovy Plugins
Atlassian Groovy PluginsAtlassian Groovy Plugins
Atlassian Groovy Plugins
 
JavaOne 2011 - JVM Bytecode for Dummies
JavaOne 2011 - JVM Bytecode for DummiesJavaOne 2011 - JVM Bytecode for Dummies
JavaOne 2011 - JVM Bytecode for Dummies
 
Down the Rabbit Hole: An Adventure in JVM Wonderland
Down the Rabbit Hole: An Adventure in JVM WonderlandDown the Rabbit Hole: An Adventure in JVM Wonderland
Down the Rabbit Hole: An Adventure in JVM Wonderland
 
Øredev 2011 - JVM JIT for Dummies (What the JVM Does With Your Bytecode When ...
Øredev 2011 - JVM JIT for Dummies (What the JVM Does With Your Bytecode When ...Øredev 2011 - JVM JIT for Dummies (What the JVM Does With Your Bytecode When ...
Øredev 2011 - JVM JIT for Dummies (What the JVM Does With Your Bytecode When ...
 
Exploring Clojurescript
Exploring ClojurescriptExploring Clojurescript
Exploring Clojurescript
 
Kotlin is charming; The reasons Java engineers should start Kotlin.
Kotlin is charming; The reasons Java engineers should start Kotlin.Kotlin is charming; The reasons Java engineers should start Kotlin.
Kotlin is charming; The reasons Java engineers should start Kotlin.
 
Spock: Test Well and Prosper
Spock: Test Well and ProsperSpock: Test Well and Prosper
Spock: Test Well and Prosper
 
Java libraries you can't afford to miss
Java libraries you can't afford to missJava libraries you can't afford to miss
Java libraries you can't afford to miss
 
Infinum android talks_10_getting groovy on android
Infinum android talks_10_getting groovy on androidInfinum android talks_10_getting groovy on android
Infinum android talks_10_getting groovy on android
 
Groovy DSLs (JavaOne Presentation)
Groovy DSLs (JavaOne Presentation)Groovy DSLs (JavaOne Presentation)
Groovy DSLs (JavaOne Presentation)
 
Gradle in a Polyglot World
Gradle in a Polyglot WorldGradle in a Polyglot World
Gradle in a Polyglot World
 
Webinar: MongoDB Persistence with Java and Morphia
Webinar: MongoDB Persistence with Java and MorphiaWebinar: MongoDB Persistence with Java and Morphia
Webinar: MongoDB Persistence with Java and Morphia
 
Flutter 是什麼?用 Flutter 會省到時間嗎? @ GDG Devfest2020
Flutter 是什麼?用 Flutter 會省到時間嗎? @ GDG Devfest2020Flutter 是什麼?用 Flutter 會省到時間嗎? @ GDG Devfest2020
Flutter 是什麼?用 Flutter 會省到時間嗎? @ GDG Devfest2020
 
Everything you wanted to know about Stack Traces and Heap Dumps
Everything you wanted to know about Stack Traces and Heap DumpsEverything you wanted to know about Stack Traces and Heap Dumps
Everything you wanted to know about Stack Traces and Heap Dumps
 
JavaOne 2012 - JVM JIT for Dummies
JavaOne 2012 - JVM JIT for DummiesJavaOne 2012 - JVM JIT for Dummies
JavaOne 2012 - JVM JIT for Dummies
 
Fun with Functional Programming in Clojure
Fun with Functional Programming in ClojureFun with Functional Programming in Clojure
Fun with Functional Programming in Clojure
 

Similar to Oscon Java Testing on the Fast Lane

Javaone2008 Bof 5101 Groovytesting
Javaone2008 Bof 5101 GroovytestingJavaone2008 Bof 5101 Groovytesting
Javaone2008 Bof 5101 Groovytesting
Andres Almiray
 
Boosting Your Testing Productivity with Groovy
Boosting Your Testing Productivity with GroovyBoosting Your Testing Productivity with Groovy
Boosting Your Testing Productivity with Groovy
James Williams
 
GTAC Boosting your Testing Productivity with Groovy
GTAC Boosting your Testing Productivity with GroovyGTAC Boosting your Testing Productivity with Groovy
GTAC Boosting your Testing Productivity with Groovy
Andres Almiray
 
Svcc Groovy Testing
Svcc Groovy TestingSvcc Groovy Testing
Svcc Groovy Testing
Andres Almiray
 
2007 09 10 Fzi Training Groovy Grails V Ws
2007 09 10 Fzi Training Groovy Grails V Ws2007 09 10 Fzi Training Groovy Grails V Ws
2007 09 10 Fzi Training Groovy Grails V Ws
loffenauer
 
An Introduction to Gradle for Java Developers
An Introduction to Gradle for Java DevelopersAn Introduction to Gradle for Java Developers
An Introduction to Gradle for Java Developers
Kostas Saidis
 
Groovy & Grails
Groovy & GrailsGroovy & Grails
Groovy & Grails
Marcel Overdijk
 
Groovy - Grails as a modern scripting language for Web applications
Groovy - Grails as a modern scripting language for Web applicationsGroovy - Grails as a modern scripting language for Web applications
Groovy - Grails as a modern scripting language for Web applications
IndicThreads
 
Groovy & Grails: Scripting for Modern Web Applications
Groovy & Grails: Scripting for Modern Web ApplicationsGroovy & Grails: Scripting for Modern Web Applications
Groovy & Grails: Scripting for Modern Web Applications
rohitnayak
 
Модерни езици за програмиране за JVM (2011)
Модерни езици за програмиране за JVM (2011)Модерни езици за програмиране за JVM (2011)
Модерни езици за програмиране за JVM (2011)
Bozhidar Batsov
 
What's New in Groovy 1.6?
What's New in Groovy 1.6?What's New in Groovy 1.6?
What's New in Groovy 1.6?
Guillaume Laforge
 
Apache Groovy: the language and the ecosystem
Apache Groovy: the language and the ecosystemApache Groovy: the language and the ecosystem
Apache Groovy: the language and the ecosystem
Kostas Saidis
 
Gradle For Beginners (Serbian Developer Conference 2013 english)
Gradle For Beginners (Serbian Developer Conference 2013 english)Gradle For Beginners (Serbian Developer Conference 2013 english)
Gradle For Beginners (Serbian Developer Conference 2013 english)
Joachim Baumann
 
Industrial Strength Groovy - Tools for the Professional Groovy Developer: Pau...
Industrial Strength Groovy - Tools for the Professional Groovy Developer: Pau...Industrial Strength Groovy - Tools for the Professional Groovy Developer: Pau...
Industrial Strength Groovy - Tools for the Professional Groovy Developer: Pau...
Paul King
 
Introduction to Oracle Groovy
Introduction to Oracle GroovyIntroduction to Oracle Groovy
Introduction to Oracle Groovy
Deepak Bhagat
 
Eclipsecon08 Introduction To Groovy
Eclipsecon08 Introduction To GroovyEclipsecon08 Introduction To Groovy
Eclipsecon08 Introduction To Groovy
Andres Almiray
 
Groovy a Scripting Language for Java
Groovy a Scripting Language for JavaGroovy a Scripting Language for Java
Groovy a Scripting Language for Java
Charles Anderson
 
OpenLogic
OpenLogicOpenLogic
OpenLogic
webuploader
 
Building Atlassian Plugins with Groovy - Atlassian Summit 2010 - Lightning Talks
Building Atlassian Plugins with Groovy - Atlassian Summit 2010 - Lightning TalksBuilding Atlassian Plugins with Groovy - Atlassian Summit 2010 - Lightning Talks
Building Atlassian Plugins with Groovy - Atlassian Summit 2010 - Lightning Talks
Atlassian
 
Groovy for Java Developers
Groovy for Java DevelopersGroovy for Java Developers
Groovy for Java Developers
Andres Almiray
 

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

Javaone2008 Bof 5101 Groovytesting
Javaone2008 Bof 5101 GroovytestingJavaone2008 Bof 5101 Groovytesting
Javaone2008 Bof 5101 Groovytesting
 
Boosting Your Testing Productivity with Groovy
Boosting Your Testing Productivity with GroovyBoosting Your Testing Productivity with Groovy
Boosting Your Testing Productivity with Groovy
 
GTAC Boosting your Testing Productivity with Groovy
GTAC Boosting your Testing Productivity with GroovyGTAC Boosting your Testing Productivity with Groovy
GTAC Boosting your Testing Productivity with Groovy
 
Svcc Groovy Testing
Svcc Groovy TestingSvcc Groovy Testing
Svcc Groovy Testing
 
2007 09 10 Fzi Training Groovy Grails V Ws
2007 09 10 Fzi Training Groovy Grails V Ws2007 09 10 Fzi Training Groovy Grails V Ws
2007 09 10 Fzi Training Groovy Grails V Ws
 
An Introduction to Gradle for Java Developers
An Introduction to Gradle for Java DevelopersAn Introduction to Gradle for Java Developers
An Introduction to Gradle for Java Developers
 
Groovy & Grails
Groovy & GrailsGroovy & Grails
Groovy & Grails
 
Groovy - Grails as a modern scripting language for Web applications
Groovy - Grails as a modern scripting language for Web applicationsGroovy - Grails as a modern scripting language for Web applications
Groovy - Grails as a modern scripting language for Web applications
 
Groovy & Grails: Scripting for Modern Web Applications
Groovy & Grails: Scripting for Modern Web ApplicationsGroovy & Grails: Scripting for Modern Web Applications
Groovy & Grails: Scripting for Modern Web Applications
 
Модерни езици за програмиране за JVM (2011)
Модерни езици за програмиране за JVM (2011)Модерни езици за програмиране за JVM (2011)
Модерни езици за програмиране за JVM (2011)
 
What's New in Groovy 1.6?
What's New in Groovy 1.6?What's New in Groovy 1.6?
What's New in Groovy 1.6?
 
Apache Groovy: the language and the ecosystem
Apache Groovy: the language and the ecosystemApache Groovy: the language and the ecosystem
Apache Groovy: the language and the ecosystem
 
Gradle For Beginners (Serbian Developer Conference 2013 english)
Gradle For Beginners (Serbian Developer Conference 2013 english)Gradle For Beginners (Serbian Developer Conference 2013 english)
Gradle For Beginners (Serbian Developer Conference 2013 english)
 
Industrial Strength Groovy - Tools for the Professional Groovy Developer: Pau...
Industrial Strength Groovy - Tools for the Professional Groovy Developer: Pau...Industrial Strength Groovy - Tools for the Professional Groovy Developer: Pau...
Industrial Strength Groovy - Tools for the Professional Groovy Developer: Pau...
 
Introduction to Oracle Groovy
Introduction to Oracle GroovyIntroduction to Oracle Groovy
Introduction to Oracle Groovy
 
Eclipsecon08 Introduction To Groovy
Eclipsecon08 Introduction To GroovyEclipsecon08 Introduction To Groovy
Eclipsecon08 Introduction To Groovy
 
Groovy a Scripting Language for Java
Groovy a Scripting Language for JavaGroovy a Scripting Language for Java
Groovy a Scripting Language for Java
 
OpenLogic
OpenLogicOpenLogic
OpenLogic
 
Building Atlassian Plugins with Groovy - Atlassian Summit 2010 - Lightning Talks
Building Atlassian Plugins with Groovy - Atlassian Summit 2010 - Lightning TalksBuilding Atlassian Plugins with Groovy - Atlassian Summit 2010 - Lightning Talks
Building Atlassian Plugins with Groovy - Atlassian Summit 2010 - Lightning Talks
 
Groovy for Java Developers
Groovy for Java DevelopersGroovy for Java Developers
Groovy for Java Developers
 

More from Andres Almiray

Creando, creciendo, y manteniendo una comunidad de codigo abierto
Creando, creciendo, y manteniendo una comunidad de codigo abiertoCreando, creciendo, y manteniendo una comunidad de codigo abierto
Creando, creciendo, y manteniendo una comunidad de codigo abierto
Andres Almiray
 
Liberando a produccion con confianza
Liberando a produccion con confianzaLiberando a produccion con confianza
Liberando a produccion con confianza
Andres Almiray
 
Liberando a produccion con confidencia
Liberando a produccion con confidenciaLiberando a produccion con confidencia
Liberando a produccion con confidencia
Andres Almiray
 
OracleDB Ecosystem for Java Developers
OracleDB Ecosystem for Java DevelopersOracleDB Ecosystem for Java Developers
OracleDB Ecosystem for Java Developers
Andres Almiray
 
Softcon.ph - Maven Puzzlers
Softcon.ph - Maven PuzzlersSoftcon.ph - Maven Puzzlers
Softcon.ph - Maven Puzzlers
Andres Almiray
 
Maven Puzzlers
Maven PuzzlersMaven Puzzlers
Maven Puzzlers
Andres Almiray
 
Oracle Database Ecosystem for Java Developers
Oracle Database Ecosystem for Java DevelopersOracle Database Ecosystem for Java Developers
Oracle Database Ecosystem for Java Developers
Andres Almiray
 
JReleaser - Releasing at the speed of light
JReleaser - Releasing at the speed of lightJReleaser - Releasing at the speed of light
JReleaser - Releasing at the speed of light
Andres Almiray
 
Building modular applications with the Java Platform Module System and Layrry
Building modular applications with the Java Platform Module System and LayrryBuilding modular applications with the Java Platform Module System and Layrry
Building modular applications with the Java Platform Module System and Layrry
Andres Almiray
 
Going Reactive with g rpc
Going Reactive with g rpcGoing Reactive with g rpc
Going Reactive with g rpc
Andres Almiray
 
Building modular applications with JPMS and Layrry
Building modular applications with JPMS and LayrryBuilding modular applications with JPMS and Layrry
Building modular applications with JPMS and Layrry
Andres Almiray
 
Taking Micronaut out for a spin
Taking Micronaut out for a spinTaking Micronaut out for a spin
Taking Micronaut out for a spin
Andres Almiray
 
Apache Groovy's Metaprogramming Options and You
Apache Groovy's Metaprogramming Options and YouApache Groovy's Metaprogramming Options and You
Apache Groovy's Metaprogramming Options and You
Andres Almiray
 
What I wish I knew about Maven years ago
What I wish I knew about Maven years agoWhat I wish I knew about Maven years ago
What I wish I knew about Maven years ago
Andres Almiray
 
What I wish I knew about maven years ago
What I wish I knew about maven years agoWhat I wish I knew about maven years ago
What I wish I knew about maven years ago
Andres Almiray
 
The impact of sci fi in tech
The impact of sci fi in techThe impact of sci fi in tech
The impact of sci fi in tech
Andres Almiray
 
Gradle Ex Machina - Devoxx 2019
Gradle Ex Machina - Devoxx 2019Gradle Ex Machina - Devoxx 2019
Gradle Ex Machina - Devoxx 2019
Andres Almiray
 
Creating Better Builds with Gradle
Creating Better Builds with GradleCreating Better Builds with Gradle
Creating Better Builds with Gradle
Andres Almiray
 
Interacting with the Oracle Cloud Java SDK with Gradle
Interacting with the Oracle Cloud Java SDK with GradleInteracting with the Oracle Cloud Java SDK with Gradle
Interacting with the Oracle Cloud Java SDK with Gradle
Andres Almiray
 
Gradle ex-machina
Gradle ex-machinaGradle ex-machina
Gradle ex-machina
Andres Almiray
 

More from Andres Almiray (20)

Creando, creciendo, y manteniendo una comunidad de codigo abierto
Creando, creciendo, y manteniendo una comunidad de codigo abiertoCreando, creciendo, y manteniendo una comunidad de codigo abierto
Creando, creciendo, y manteniendo una comunidad de codigo abierto
 
Liberando a produccion con confianza
Liberando a produccion con confianzaLiberando a produccion con confianza
Liberando a produccion con confianza
 
Liberando a produccion con confidencia
Liberando a produccion con confidenciaLiberando a produccion con confidencia
Liberando a produccion con confidencia
 
OracleDB Ecosystem for Java Developers
OracleDB Ecosystem for Java DevelopersOracleDB Ecosystem for Java Developers
OracleDB Ecosystem for Java Developers
 
Softcon.ph - Maven Puzzlers
Softcon.ph - Maven PuzzlersSoftcon.ph - Maven Puzzlers
Softcon.ph - Maven Puzzlers
 
Maven Puzzlers
Maven PuzzlersMaven Puzzlers
Maven Puzzlers
 
Oracle Database Ecosystem for Java Developers
Oracle Database Ecosystem for Java DevelopersOracle Database Ecosystem for Java Developers
Oracle Database Ecosystem for Java Developers
 
JReleaser - Releasing at the speed of light
JReleaser - Releasing at the speed of lightJReleaser - Releasing at the speed of light
JReleaser - Releasing at the speed of light
 
Building modular applications with the Java Platform Module System and Layrry
Building modular applications with the Java Platform Module System and LayrryBuilding modular applications with the Java Platform Module System and Layrry
Building modular applications with the Java Platform Module System and Layrry
 
Going Reactive with g rpc
Going Reactive with g rpcGoing Reactive with g rpc
Going Reactive with g rpc
 
Building modular applications with JPMS and Layrry
Building modular applications with JPMS and LayrryBuilding modular applications with JPMS and Layrry
Building modular applications with JPMS and Layrry
 
Taking Micronaut out for a spin
Taking Micronaut out for a spinTaking Micronaut out for a spin
Taking Micronaut out for a spin
 
Apache Groovy's Metaprogramming Options and You
Apache Groovy's Metaprogramming Options and YouApache Groovy's Metaprogramming Options and You
Apache Groovy's Metaprogramming Options and You
 
What I wish I knew about Maven years ago
What I wish I knew about Maven years agoWhat I wish I knew about Maven years ago
What I wish I knew about Maven years ago
 
What I wish I knew about maven years ago
What I wish I knew about maven years agoWhat I wish I knew about maven years ago
What I wish I knew about maven years ago
 
The impact of sci fi in tech
The impact of sci fi in techThe impact of sci fi in tech
The impact of sci fi in tech
 
Gradle Ex Machina - Devoxx 2019
Gradle Ex Machina - Devoxx 2019Gradle Ex Machina - Devoxx 2019
Gradle Ex Machina - Devoxx 2019
 
Creating Better Builds with Gradle
Creating Better Builds with GradleCreating Better Builds with Gradle
Creating Better Builds with Gradle
 
Interacting with the Oracle Cloud Java SDK with Gradle
Interacting with the Oracle Cloud Java SDK with GradleInteracting with the Oracle Cloud Java SDK with Gradle
Interacting with the Oracle Cloud Java SDK with Gradle
 
Gradle ex-machina
Gradle ex-machinaGradle ex-machina
Gradle ex-machina
 

Recently uploaded

How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdfHow to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
Chart Kalyan
 
Fueling AI with Great Data with Airbyte Webinar
Fueling AI with Great Data with Airbyte WebinarFueling AI with Great Data with Airbyte Webinar
Fueling AI with Great Data with Airbyte Webinar
Zilliz
 
Nordic Marketo Engage User Group_June 13_ 2024.pptx
Nordic Marketo Engage User Group_June 13_ 2024.pptxNordic Marketo Engage User Group_June 13_ 2024.pptx
Nordic Marketo Engage User Group_June 13_ 2024.pptx
MichaelKnudsen27
 
Recommendation System using RAG Architecture
Recommendation System using RAG ArchitectureRecommendation System using RAG Architecture
Recommendation System using RAG Architecture
fredae14
 
WeTestAthens: Postman's AI & Automation Techniques
WeTestAthens: Postman's AI & Automation TechniquesWeTestAthens: Postman's AI & Automation Techniques
WeTestAthens: Postman's AI & Automation Techniques
Postman
 
Columbus Data & Analytics Wednesdays - June 2024
Columbus Data & Analytics Wednesdays - June 2024Columbus Data & Analytics Wednesdays - June 2024
Columbus Data & Analytics Wednesdays - June 2024
Jason Packer
 
5th LF Energy Power Grid Model Meet-up Slides
5th LF Energy Power Grid Model Meet-up Slides5th LF Energy Power Grid Model Meet-up Slides
5th LF Energy Power Grid Model Meet-up Slides
DanBrown980551
 
Serial Arm Control in Real Time Presentation
Serial Arm Control in Real Time PresentationSerial Arm Control in Real Time Presentation
Serial Arm Control in Real Time Presentation
tolgahangng
 
Building Production Ready Search Pipelines with Spark and Milvus
Building Production Ready Search Pipelines with Spark and MilvusBuilding Production Ready Search Pipelines with Spark and Milvus
Building Production Ready Search Pipelines with Spark and Milvus
Zilliz
 
Letter and Document Automation for Bonterra Impact Management (fka Social Sol...
Letter and Document Automation for Bonterra Impact Management (fka Social Sol...Letter and Document Automation for Bonterra Impact Management (fka Social Sol...
Letter and Document Automation for Bonterra Impact Management (fka Social Sol...
Jeffrey Haguewood
 
Operating System Used by Users in day-to-day life.pptx
Operating System Used by Users in day-to-day life.pptxOperating System Used by Users in day-to-day life.pptx
Operating System Used by Users in day-to-day life.pptx
Pravash Chandra Das
 
Monitoring and Managing Anomaly Detection on OpenShift.pdf
Monitoring and Managing Anomaly Detection on OpenShift.pdfMonitoring and Managing Anomaly Detection on OpenShift.pdf
Monitoring and Managing Anomaly Detection on OpenShift.pdf
Tosin Akinosho
 
TrustArc Webinar - 2024 Global Privacy Survey
TrustArc Webinar - 2024 Global Privacy SurveyTrustArc Webinar - 2024 Global Privacy Survey
TrustArc Webinar - 2024 Global Privacy Survey
TrustArc
 
UI5 Controls simplified - UI5con2024 presentation
UI5 Controls simplified - UI5con2024 presentationUI5 Controls simplified - UI5con2024 presentation
UI5 Controls simplified - UI5con2024 presentation
Wouter Lemaire
 
Deep Dive: Getting Funded with Jason Jason Lemkin Founder & CEO @ SaaStr
Deep Dive: Getting Funded with Jason Jason Lemkin Founder & CEO @ SaaStrDeep Dive: Getting Funded with Jason Jason Lemkin Founder & CEO @ SaaStr
Deep Dive: Getting Funded with Jason Jason Lemkin Founder & CEO @ SaaStr
saastr
 
Main news related to the CCS TSI 2023 (2023/1695)
Main news related to the CCS TSI 2023 (2023/1695)Main news related to the CCS TSI 2023 (2023/1695)
Main news related to the CCS TSI 2023 (2023/1695)
Jakub Marek
 
leewayhertz.com-AI in predictive maintenance Use cases technologies benefits ...
leewayhertz.com-AI in predictive maintenance Use cases technologies benefits ...leewayhertz.com-AI in predictive maintenance Use cases technologies benefits ...
leewayhertz.com-AI in predictive maintenance Use cases technologies benefits ...
alexjohnson7307
 
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdfUnlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
Malak Abu Hammad
 
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAUHCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
panagenda
 
dbms calicut university B. sc Cs 4th sem.pdf
dbms  calicut university B. sc Cs 4th sem.pdfdbms  calicut university B. sc Cs 4th sem.pdf
dbms calicut university B. sc Cs 4th sem.pdf
Shinana2
 

Recently uploaded (20)

How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdfHow to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
 
Fueling AI with Great Data with Airbyte Webinar
Fueling AI with Great Data with Airbyte WebinarFueling AI with Great Data with Airbyte Webinar
Fueling AI with Great Data with Airbyte Webinar
 
Nordic Marketo Engage User Group_June 13_ 2024.pptx
Nordic Marketo Engage User Group_June 13_ 2024.pptxNordic Marketo Engage User Group_June 13_ 2024.pptx
Nordic Marketo Engage User Group_June 13_ 2024.pptx
 
Recommendation System using RAG Architecture
Recommendation System using RAG ArchitectureRecommendation System using RAG Architecture
Recommendation System using RAG Architecture
 
WeTestAthens: Postman's AI & Automation Techniques
WeTestAthens: Postman's AI & Automation TechniquesWeTestAthens: Postman's AI & Automation Techniques
WeTestAthens: Postman's AI & Automation Techniques
 
Columbus Data & Analytics Wednesdays - June 2024
Columbus Data & Analytics Wednesdays - June 2024Columbus Data & Analytics Wednesdays - June 2024
Columbus Data & Analytics Wednesdays - June 2024
 
5th LF Energy Power Grid Model Meet-up Slides
5th LF Energy Power Grid Model Meet-up Slides5th LF Energy Power Grid Model Meet-up Slides
5th LF Energy Power Grid Model Meet-up Slides
 
Serial Arm Control in Real Time Presentation
Serial Arm Control in Real Time PresentationSerial Arm Control in Real Time Presentation
Serial Arm Control in Real Time Presentation
 
Building Production Ready Search Pipelines with Spark and Milvus
Building Production Ready Search Pipelines with Spark and MilvusBuilding Production Ready Search Pipelines with Spark and Milvus
Building Production Ready Search Pipelines with Spark and Milvus
 
Letter and Document Automation for Bonterra Impact Management (fka Social Sol...
Letter and Document Automation for Bonterra Impact Management (fka Social Sol...Letter and Document Automation for Bonterra Impact Management (fka Social Sol...
Letter and Document Automation for Bonterra Impact Management (fka Social Sol...
 
Operating System Used by Users in day-to-day life.pptx
Operating System Used by Users in day-to-day life.pptxOperating System Used by Users in day-to-day life.pptx
Operating System Used by Users in day-to-day life.pptx
 
Monitoring and Managing Anomaly Detection on OpenShift.pdf
Monitoring and Managing Anomaly Detection on OpenShift.pdfMonitoring and Managing Anomaly Detection on OpenShift.pdf
Monitoring and Managing Anomaly Detection on OpenShift.pdf
 
TrustArc Webinar - 2024 Global Privacy Survey
TrustArc Webinar - 2024 Global Privacy SurveyTrustArc Webinar - 2024 Global Privacy Survey
TrustArc Webinar - 2024 Global Privacy Survey
 
UI5 Controls simplified - UI5con2024 presentation
UI5 Controls simplified - UI5con2024 presentationUI5 Controls simplified - UI5con2024 presentation
UI5 Controls simplified - UI5con2024 presentation
 
Deep Dive: Getting Funded with Jason Jason Lemkin Founder & CEO @ SaaStr
Deep Dive: Getting Funded with Jason Jason Lemkin Founder & CEO @ SaaStrDeep Dive: Getting Funded with Jason Jason Lemkin Founder & CEO @ SaaStr
Deep Dive: Getting Funded with Jason Jason Lemkin Founder & CEO @ SaaStr
 
Main news related to the CCS TSI 2023 (2023/1695)
Main news related to the CCS TSI 2023 (2023/1695)Main news related to the CCS TSI 2023 (2023/1695)
Main news related to the CCS TSI 2023 (2023/1695)
 
leewayhertz.com-AI in predictive maintenance Use cases technologies benefits ...
leewayhertz.com-AI in predictive maintenance Use cases technologies benefits ...leewayhertz.com-AI in predictive maintenance Use cases technologies benefits ...
leewayhertz.com-AI in predictive maintenance Use cases technologies benefits ...
 
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdfUnlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
 
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAUHCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
 
dbms calicut university B. sc Cs 4th sem.pdf
dbms  calicut university B. sc Cs 4th sem.pdfdbms  calicut university B. sc Cs 4th sem.pdf
dbms calicut university B. sc Cs 4th sem.pdf
 

Oscon Java Testing on the Fast Lane

  • 1. Java Testing on the Fast Lane
  • 2. Be more effective while programming tests (and have some fun too!) Goal
  • 3. About the presenter • Java Developer since the beginning • Open Source believer since 1997 • Groovy development team member since 2007 • Griffon project co-founder
  • 4. Agenda •What is Groovy •Groovy + Testing Frameworks •How Groovy helps •Mocking with Groovy •XML Processing •Functional UI Testing •Resources
  • 5. 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
  • 6. 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
  • 7. 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() ); } }
  • 8. 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() ); } }
  • 9. Equivalent HelloWorld 100% Groovy class HelloWorld { String name def greet() { "Hello $name" } } def helloWorld = new HelloWorld(name:"Groovy") println helloWorld.greet()
  • 10. 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.
  • 11. 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).
  • 12. 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!
  • 13. 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
  • 14. 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
  • 15. 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()
  • 16. 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
  • 17. 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
  • 18. 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
  • 19. 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)
  • 20. AST Transformations • @Singleton • @Lazy • @Delegate • @Immutable • @Bindable • @Newify • @Category/@Mixin • @PackageScope
  • 21. 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
  • 22. 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 } } }
  • 23. Testing exceptions in Groovy class GroovyExceptionTestCase extends GroovyTestCase { void testExceptionThrowingCode() { shouldFail( UnsupportedOperationException ){ new MyService().doSomething() } } }
  • 24. 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)
  • 26.
  • 27. 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.
  • 29.
  • 30. 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
  • 31. 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() } }
  • 32. 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() } }
  • 33. 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
  • 34. Groovy to the rescue! • Web: • Canoo WebTest - leverages AntBuilder • Tellurium - a Groovier Selenium • Desktop: • FEST – next generation Swing testing • BDD: • Easyb • Spock
  • 37. Q&A