SlideShare a Scribd company logo
Cucumber on the JVM with
              Groovy
          cucumber, cuke4duke, groovy, geb




Richard Paul                             2011-03-24
What is Groovy

•   Dynamic language for the JVM
•   Inspired by Python, Ruby, Smalltalk
•   Integrates closely with Java
•   Superset of Java syntax




http://groovy.codehaus.org/
Why Groovy

•   Leverage existing Java API knowledge
•   Integrate closely with production Java code
•   Expressive language & libraries
•   Just a 5MB jar on the classpath
Groovy Support in Cucumber

• Cuke4Duke
• Uses JRuby behind the scenes
  o Pure Java coming later this year
• Groovy DSL to automate scenarios




https://github.com/aslakhellesoy/cuke4duke
Feature

Scenario: Regular numbers
  Given I have entered 3
  And I have entered 2
  When I press divide
  Then the result should be 1.5




https://github.com/aslakhellesoy/cuke4duke/tree/master/examples/groovy
Given


Given(~'I have entered (.*)') { number ->
    calculator.push number
}



// Implicit coercion to integer
Given(~'I have entered (.*)') { int number ->
    assert number.class == Integer.class
    calculator.push number
}
When


When(~'I press (w+)') { operatorName ->
    result = calculator."$operatorName"()
}



// Can use slashy strings to avoid escaping
When(/I press (w+)/) { operatorName ->
    result = calculator."$operatorName"()
}
Then


Then(~'the result should be (.*)') {
        double result ->
    assert expected == result
}


// == compares equality
// not same instance as in Java
Power Assert

def now = new Date()
def old = Date.parse('yyyyMMdd', '20100101')
assert now.date == old.date



Assertion failed:

assert now.date == old.date
       |   |    | |    |
       |   19   | |    1
       |        | Fri Jan 01 00:00:00 GMT 2010
       |        false
       Sat Mar 19 13:18:42 GMT 2011
Multiline Strings

Given some text
"""
Line 1
Line 2
"""

Given(~'some text') { body ->
    body.eachLine {
        println it
    }
}

=> Line 1
=> Line 2
Tables

Given I have the following foods
  |name |healthy|
  |Orange|Yes    |
  |Chips |No     |
When I count the number of healthy items
Then I have 1 healthy item
Tables

Given(~'I have the following foods') { table ->
    basket = new Basket()
    table.hashes().each {
        def item = new Food(
            name:    it.name, // it.get('name')
            healthy: it.healthy == 'Yes')
        basket.add(item)
    }
}
When(~'I count the healthy items') {
    numberOfHealthy = basket.numberOfHealthy
}
Then(~'I have (.+) healthy items') { int count ->
    assert numberOfHealthy == count
}
Tables

class Basket {
    private items = []
    void add(item) {
        items << item
    }
    int getNumberOfHealthy() {
        items.findAll {
            it.healthy
        }.size()
    }
}

class Food {
    def name
    def healthy
}
Organising Step Definitions

Cucumber will read in any .groovy files within step_definitions

All steps are then available to any scenarios

State can be shared between steps by setting to script binding

When(~'I set a variable to the binding') {
    x = 1
}
Then(~'the other step can access variable') {
    assert x == 1
}
Before/After

Before {
  // Initialise something
}

Before('@tagname') {
  // Initialise only for features/scenarios
  // tagged with @tagname
}
Before('~@tagname') {} // not tagged

After {
  // Clean up something
}
World

Allow simple access to methods from within step definitions


World {
    def world = new Object()
    world.metaClass.mixin Math
    world
}


When(~'we take the square root') {
    sqrt(4)    // calls Math.sqrt(4)
}
Browser Automation with Geb

Given(~'I am on the Wikipedia homepage') {
    go()
}

When(~'I search for "(.+)"') { query ->
    $('#searchInput').value(query)
    $('.searchButton').click()
}

Then(~'I am shown the "(.+)" article') { article ->
    assert $('h1').text() == article
}
env.groovy for Geb

import geb.Browser
this.metaClass.mixin(cuke4duke.GroovyDsl)

World {
    new Browser('http://wikipedia.org')
}

After {
    clearCookies()
}
Build Tools

Integration with
 • Maven
 • Ant

Cucumber can write reports in JUnit format for CI reports
Discussion/Questions




                   Thanks!

         http://rapaul.com      @rapaul

More Related Content

PDF
ES6 generators
PDF
Introduction kot iin
PDF
Miracle of std lib
PDF
Javascript ES6 generators
PDF
はじめてのGroovy
PDF
Clojure functions midje
PDF
名古屋SGGAE/J勉強会 Grails、Gaelykでハンズオン
PDF
多治見IT勉強会 Groovy Grails
ES6 generators
Introduction kot iin
Miracle of std lib
Javascript ES6 generators
はじめてのGroovy
Clojure functions midje
名古屋SGGAE/J勉強会 Grails、Gaelykでハンズオン
多治見IT勉強会 Groovy Grails

What's hot (19)

PDF
Python my SQL - create table
PDF
Python my sql database connection
PDF
GPars For Beginners
PPTX
TDD in the wild
PDF
Productive Programming in Groovy
PDF
Selenium cheat sheet
PDF
Auto-GWT : Better GWT Programming with Xtend
PDF
C++ course start
KEY
Gwt and Xtend
PPSX
NOTEPAD MAKING IN PAYTHON 2ND PART BY ROHIT MALAV
PPTX
Psycopg2 - Connect to PostgreSQL using Python Script
PDF
Python in the database
ODP
FRP and Bacon.js
DOCX
Service Functions
ODP
Meetup slides
PDF
FrontendLab: Programming UI with FRP and Bacon js - Вячеслав Ворончук
PPTX
Voldemort collections library
PPTX
Grails queries
PPTX
Python my SQL - create table
Python my sql database connection
GPars For Beginners
TDD in the wild
Productive Programming in Groovy
Selenium cheat sheet
Auto-GWT : Better GWT Programming with Xtend
C++ course start
Gwt and Xtend
NOTEPAD MAKING IN PAYTHON 2ND PART BY ROHIT MALAV
Psycopg2 - Connect to PostgreSQL using Python Script
Python in the database
FRP and Bacon.js
Service Functions
Meetup slides
FrontendLab: Programming UI with FRP and Bacon js - Вячеслав Ворончук
Voldemort collections library
Grails queries
Ad

Viewers also liked (8)

ODP
Test Automation Framework using Cucumber BDD overview (part 1)
PPTX
Is Groovy better for testing than Java?
PDF
Cucumber in Practice(en)
PDF
RSpec & TDD Tutorial
PDF
Cucumber ppt
PPTX
Test automation with Cucumber-JVM
PDF
Introduction to BDD with Cucumber for Java
PPTX
Cucumber_Training_ForQA
Test Automation Framework using Cucumber BDD overview (part 1)
Is Groovy better for testing than Java?
Cucumber in Practice(en)
RSpec & TDD Tutorial
Cucumber ppt
Test automation with Cucumber-JVM
Introduction to BDD with Cucumber for Java
Cucumber_Training_ForQA
Ad

Similar to Cucumber on the JVM with Groovy (20)

PPTX
Cucumber presenation
PPTX
Test Driven In Groovy
PDF
Oscon Java Testing on the Fast Lane
PDF
Groovy On Trading Desk (2010)
PDF
Groovy.pptx
PDF
Groovy Fly Through
KEY
Introduction to Groovy
PDF
Acceptance testing with Geb
PDF
Introduction to Groovy (Serbian Developer Conference 2013)
PDF
淺談 Groovy 與 AWS 雲端應用開發整合
ODP
BDD with Cucumber
KEY
Cucumber, Cuke4Duke, and Groovy
PDF
Behaviour driven infrastructure
PDF
Groovy and Grails talk
PPT
Svcc Groovy Testing
PPT
GTAC Boosting your Testing Productivity with Groovy
PPTX
Cucumber jvm best practices v3
PDF
Javantura v2 - Making Java web-apps Groovy - Franjo Žilić
PPT
Cucumber presentation
PPT
2007 09 10 Fzi Training Groovy Grails V Ws
Cucumber presenation
Test Driven In Groovy
Oscon Java Testing on the Fast Lane
Groovy On Trading Desk (2010)
Groovy.pptx
Groovy Fly Through
Introduction to Groovy
Acceptance testing with Geb
Introduction to Groovy (Serbian Developer Conference 2013)
淺談 Groovy 與 AWS 雲端應用開發整合
BDD with Cucumber
Cucumber, Cuke4Duke, and Groovy
Behaviour driven infrastructure
Groovy and Grails talk
Svcc Groovy Testing
GTAC Boosting your Testing Productivity with Groovy
Cucumber jvm best practices v3
Javantura v2 - Making Java web-apps Groovy - Franjo Žilić
Cucumber presentation
2007 09 10 Fzi Training Groovy Grails V Ws

More from Richard Paul (8)

PDF
Acceptance tests
PDF
jQuery Behaviours
PDF
Introduction to Spring's Dependency Injection
PDF
Introduction to Spring MVC
PDF
Unit Testing Fundamentals
PDF
Using Dojo
PDF
Javascript & Ajax Basics
PDF
Mocking in Java with Mockito
Acceptance tests
jQuery Behaviours
Introduction to Spring's Dependency Injection
Introduction to Spring MVC
Unit Testing Fundamentals
Using Dojo
Javascript & Ajax Basics
Mocking in Java with Mockito

Recently uploaded (20)

PDF
Machine learning based COVID-19 study performance prediction
PPTX
Machine Learning_overview_presentation.pptx
PDF
Accuracy of neural networks in brain wave diagnosis of schizophrenia
PDF
gpt5_lecture_notes_comprehensive_20250812015547.pdf
PDF
Network Security Unit 5.pdf for BCA BBA.
PPTX
1. Introduction to Computer Programming.pptx
PPTX
TechTalks-8-2019-Service-Management-ITIL-Refresh-ITIL-4-Framework-Supports-Ou...
PDF
Spectral efficient network and resource selection model in 5G networks
PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
PDF
Approach and Philosophy of On baking technology
PDF
Reach Out and Touch Someone: Haptics and Empathic Computing
PDF
Mushroom cultivation and it's methods.pdf
PPTX
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
PDF
Video forgery: An extensive analysis of inter-and intra-frame manipulation al...
PDF
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
PDF
Encapsulation theory and applications.pdf
PDF
Empathic Computing: Creating Shared Understanding
PPTX
SOPHOS-XG Firewall Administrator PPT.pptx
PDF
August Patch Tuesday
PPTX
OMC Textile Division Presentation 2021.pptx
Machine learning based COVID-19 study performance prediction
Machine Learning_overview_presentation.pptx
Accuracy of neural networks in brain wave diagnosis of schizophrenia
gpt5_lecture_notes_comprehensive_20250812015547.pdf
Network Security Unit 5.pdf for BCA BBA.
1. Introduction to Computer Programming.pptx
TechTalks-8-2019-Service-Management-ITIL-Refresh-ITIL-4-Framework-Supports-Ou...
Spectral efficient network and resource selection model in 5G networks
Diabetes mellitus diagnosis method based random forest with bat algorithm
Approach and Philosophy of On baking technology
Reach Out and Touch Someone: Haptics and Empathic Computing
Mushroom cultivation and it's methods.pdf
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
Video forgery: An extensive analysis of inter-and intra-frame manipulation al...
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
Encapsulation theory and applications.pdf
Empathic Computing: Creating Shared Understanding
SOPHOS-XG Firewall Administrator PPT.pptx
August Patch Tuesday
OMC Textile Division Presentation 2021.pptx

Cucumber on the JVM with Groovy

  • 1. Cucumber on the JVM with Groovy cucumber, cuke4duke, groovy, geb Richard Paul 2011-03-24
  • 2. What is Groovy • Dynamic language for the JVM • Inspired by Python, Ruby, Smalltalk • Integrates closely with Java • Superset of Java syntax http://groovy.codehaus.org/
  • 3. Why Groovy • Leverage existing Java API knowledge • Integrate closely with production Java code • Expressive language & libraries • Just a 5MB jar on the classpath
  • 4. Groovy Support in Cucumber • Cuke4Duke • Uses JRuby behind the scenes o Pure Java coming later this year • Groovy DSL to automate scenarios https://github.com/aslakhellesoy/cuke4duke
  • 5. Feature Scenario: Regular numbers Given I have entered 3 And I have entered 2 When I press divide Then the result should be 1.5 https://github.com/aslakhellesoy/cuke4duke/tree/master/examples/groovy
  • 6. Given Given(~'I have entered (.*)') { number -> calculator.push number } // Implicit coercion to integer Given(~'I have entered (.*)') { int number -> assert number.class == Integer.class calculator.push number }
  • 7. When When(~'I press (w+)') { operatorName -> result = calculator."$operatorName"() } // Can use slashy strings to avoid escaping When(/I press (w+)/) { operatorName -> result = calculator."$operatorName"() }
  • 8. Then Then(~'the result should be (.*)') { double result -> assert expected == result } // == compares equality // not same instance as in Java
  • 9. Power Assert def now = new Date() def old = Date.parse('yyyyMMdd', '20100101') assert now.date == old.date Assertion failed: assert now.date == old.date | | | | | | 19 | | 1 | | Fri Jan 01 00:00:00 GMT 2010 | false Sat Mar 19 13:18:42 GMT 2011
  • 10. Multiline Strings Given some text """ Line 1 Line 2 """ Given(~'some text') { body -> body.eachLine { println it } } => Line 1 => Line 2
  • 11. Tables Given I have the following foods |name |healthy| |Orange|Yes | |Chips |No | When I count the number of healthy items Then I have 1 healthy item
  • 12. Tables Given(~'I have the following foods') { table -> basket = new Basket() table.hashes().each { def item = new Food( name: it.name, // it.get('name') healthy: it.healthy == 'Yes') basket.add(item) } } When(~'I count the healthy items') { numberOfHealthy = basket.numberOfHealthy } Then(~'I have (.+) healthy items') { int count -> assert numberOfHealthy == count }
  • 13. Tables class Basket { private items = [] void add(item) { items << item } int getNumberOfHealthy() { items.findAll { it.healthy }.size() } } class Food { def name def healthy }
  • 14. Organising Step Definitions Cucumber will read in any .groovy files within step_definitions All steps are then available to any scenarios State can be shared between steps by setting to script binding When(~'I set a variable to the binding') { x = 1 } Then(~'the other step can access variable') { assert x == 1 }
  • 15. Before/After Before { // Initialise something } Before('@tagname') { // Initialise only for features/scenarios // tagged with @tagname } Before('~@tagname') {} // not tagged After { // Clean up something }
  • 16. World Allow simple access to methods from within step definitions World { def world = new Object() world.metaClass.mixin Math world } When(~'we take the square root') { sqrt(4) // calls Math.sqrt(4) }
  • 17. Browser Automation with Geb Given(~'I am on the Wikipedia homepage') { go() } When(~'I search for "(.+)"') { query -> $('#searchInput').value(query) $('.searchButton').click() } Then(~'I am shown the "(.+)" article') { article -> assert $('h1').text() == article }
  • 18. env.groovy for Geb import geb.Browser this.metaClass.mixin(cuke4duke.GroovyDsl) World { new Browser('http://wikipedia.org') } After { clearCookies() }
  • 19. Build Tools Integration with • Maven • Ant Cucumber can write reports in JUnit format for CI reports
  • 20. Discussion/Questions Thanks! http://rapaul.com      @rapaul