SlideShare una empresa de Scribd logo
1 de 39
Descargar para leer sin conexión
Spock
I have been, and always shall be, your
      friendly testing framework
Who Am I?
Ken Kousen
Kousen IT, Inc.
http://www.kousenit.com
ken.kousen@kousenit.com
@kenkousen

Making Java Groovy
http://manning.com/kousen
What is Spock?
Testing framework
  Written in Groovy

  A logical framework for enterprise testing

  Combination of
    Specification + Mock
The Search for Spock
Spock home page
  http://spockframework.org
     redirects to
  http://code.google.com/p/spock

Github
   https://github.com/spockframework/spock
Create a Spock test
Extend spock.lang.Specification

  class MySpec extends Specification
Simple Specification
Demo: Palindrome Checker
Fixture Methods

def setup() {}
   run before every feature method
def cleanup() {}
   run after every feature method
def setupSpec() {}
   run before first feature method
def cleanupSpec() {}
   run after last feature method


Like JUnit 4:
   @Before, @After,
   @BeforeClass, @AfterClass
Feature Methods
Test methods
  def "descriptive name"() {
    // blocks
  }
Blocks
setup:     cleanup:
given:

when:
  Stimulus
then:
  Response, booleans are checked

expect:    where:
when: and then:
when:
  Contents are arbitrary

then:
   conditions
   exceptions
   interactions (mocks described below)

Always occur together
what they thought old Kirk
old Method                                           would look like




Sweet method in Specification class

  expression value before
  where block

  when: obj.count()
  then:
  count == old(count) + 1


                  what he actually looks like
@Shared
Annotation for shared objects
  Note: instance fields are not shared

  @Shared res = new VeryExpensiveResource()

  @Shared sql = Sql.newInstance(...)
@Shared
Demo: Library Computer
are exceptions evil or just
Exceptions                                goatees?




thrown() and notThrown()

then:
   thrown(SqlException)
  -- or --
  SqlException e = thrown()
  e.sqlCode == ...


Can do work after catching exception
Parameterized feature methods
Tests that iterate through data
  Use where: clause

  expect: name.size() == length

  where:
  [name,length] << [['Kirk',4],['Spock',5]]
Data Table
where: clause supports data tables

  expect:    name.size() == length
  where:
   name      |   length              Shouldn't Data run on
                                          Android?

   'Kirk'    |   4
  'Spock'    |   5
  'McCoy'    |   5
where: clause
Supports anything Groovy can iterate over

  expect: x + y == z
  where:
  [x,y,z] << sql.rows('select x,y,z from ...')
@Unroll
Display separate message
   for each row of data

Spock 0.5:
  @Unroll({"...$var..."})

Spock 0.6+:
  @Unroll
  def "my test #var ..."() { ... }
Data Specs
Demos:
  Hello, Spock!
  DataDriven
  DatabaseDriven
  StadiumLocationsSpec
Interactions
Working with Mock objects




       interaction




                            NO KILL I
Creating Mocks
Two syntax options:
  def items = Mock(List)

  List items = Mock()

  Can mock interfaces with standard libs
  Mock classes with CGLIB
Setting Expectations
Use >> operator
  list.get(0) >> 'data'
Global vs Local
Global:
  Defined outside then: block
  Valid to end of feature method

Local:
  Defined inside then: block
  Valid inside preceding when: block
Optional
No cardinality
Must have return value

  then:
  list.get(0) >> 'data'
Required
Must have cardinality
May have return value

  then:
  1 * list.get(0) >> 'data'

  then:
  3 * list.size()
Cardinalities
Ranges with wildcard
  Wildcard is _ (underscore)

  3 * list.size()          // 3 times
  (3.._) * list.size()     // 3 or more
  (_..3) * list.size()     // up to 3
All sorts of constraints
Regex
  Any set method with one arg
  pojo./set.*/(_)

Nulls, not null
  pojo.method(!null)
All sorts of constraints
as Operator
  dir.listFiles(_ as FileFilter)

Closures
  count.increment { it ==~ /a*b/ }
Testing Invocation Order
Use multiple then blocks

  def 'testing order of methods'() {
    when: obj.method()

      then: 1*collaborator.method1()
      then: 1*collaborator.method2()
  }
Interactions
Demos:
  PublisherSubscriber
  TribbleSpec
Extensions
@Timeout

@Ignore

@IgnoreRest

@FailsWith
@FailsWith
Test fails with expected exception

  @FailsWith(TooFewInvocationsError)
  def "required interaction"() {
    def m = Mock(List)
    2 * m.get(_) >> "foo"
    expect: m.get(3) == "foo"
  }
@FailsWith
Parameters
  value=ExpectedExceptionOrError
  reason="reason for failure"
@Ignore and @IgnoreRest
@Ignore
  Don't run a particular test or test class
  Optional value = reason

@IgnoreRest
  Don't run any OTHER tests
interaction block
Method in Specification class
  Takes closure argument

  def 'use interaction block'() {
    when: obj.method()
    then:
    interaction {
       // do whatever
    }
  }
BDD
Behavior Driven Development
    Each block accepts string description
    Just documentation
    def "number of tribbles in storage compartment"() {
        given: "average litter of 10"
        and: "new generation every 12 hours over a period of three
days"
        when: "tribbles get into storage compartments"
        then: "compute number of tribbles"
    }
Spock's Own Tests
Like most modern open source projects

  Documentation can be thin or outdated

  Tests are excellent

     See "smoke" tests in source
Links
http://github.com/spockframework/spock
http://code.google.com/p/spock
http://spockframework.org
http://meet.spockframework.org
http://groups.google.com/group/spockframework?pli=1

Source code for examples is from
1. spock-example project
    https://github.com/spockframework/spock-example
2. my GitHub repo
    https://github.com/kousen/Spock-NFJS-Article
Session Evals
Please complete your session evals

Más contenido relacionado

La actualidad más candente

Grails/Groovyによる開発事例紹介
Grails/Groovyによる開発事例紹介Grails/Groovyによる開発事例紹介
Grails/Groovyによる開発事例紹介Kiyotaka Oku
 
Javascript Testing with Jasmine 101
Javascript Testing with Jasmine 101Javascript Testing with Jasmine 101
Javascript Testing with Jasmine 101Roy Yu
 
G*におけるソフトウェアテスト・シーズンIII
G*におけるソフトウェアテスト・シーズンIIIG*におけるソフトウェアテスト・シーズンIII
G*におけるソフトウェアテスト・シーズンIIITakuma Watabiki
 
Hear no evil, see no evil, patch no evil: Or, how to monkey-patch safely.
Hear no evil, see no evil, patch no evil: Or, how to monkey-patch safely.Hear no evil, see no evil, patch no evil: Or, how to monkey-patch safely.
Hear no evil, see no evil, patch no evil: Or, how to monkey-patch safely.Graham Dumpleton
 
Building unit tests correctly
Building unit tests correctlyBuilding unit tests correctly
Building unit tests correctlyDror Helper
 
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 missAndres Almiray
 
Effective testing with pytest
Effective testing with pytestEffective testing with pytest
Effective testing with pytestHector Canto
 
Stubる - Mockingjayを使ったHTTPクライアントのテスト -
Stubる - Mockingjayを使ったHTTPクライアントのテスト -Stubる - Mockingjayを使ったHTTPクライアントのテスト -
Stubる - Mockingjayを使ったHTTPクライアントのテスト -Kenji Tanaka
 
Jasmine - why JS tests don't smell fishy
Jasmine - why JS tests don't smell fishyJasmine - why JS tests don't smell fishy
Jasmine - why JS tests don't smell fishyIgor Napierala
 
Advance Java Programs skeleton
Advance Java Programs skeletonAdvance Java Programs skeleton
Advance Java Programs skeletonIram Ramrajkar
 
Keep your repo clean
Keep your repo cleanKeep your repo clean
Keep your repo cleanHector Canto
 
Enhanced Web Service Testing: A Better Mock Structure
Enhanced Web Service Testing: A Better Mock StructureEnhanced Web Service Testing: A Better Mock Structure
Enhanced Web Service Testing: A Better Mock StructureSalesforce Developers
 
Programming with Python and PostgreSQL
Programming with Python and PostgreSQLProgramming with Python and PostgreSQL
Programming with Python and PostgreSQLPeter Eisentraut
 

La actualidad más candente (20)

Ggug spock
Ggug spockGgug spock
Ggug spock
 
Grails/Groovyによる開発事例紹介
Grails/Groovyによる開発事例紹介Grails/Groovyによる開発事例紹介
Grails/Groovyによる開発事例紹介
 
Spock
SpockSpock
Spock
 
Celery
CeleryCelery
Celery
 
Automation patterns on practice
Automation patterns on practiceAutomation patterns on practice
Automation patterns on practice
 
Unit testing
Unit testingUnit testing
Unit testing
 
Javascript Testing with Jasmine 101
Javascript Testing with Jasmine 101Javascript Testing with Jasmine 101
Javascript Testing with Jasmine 101
 
G*におけるソフトウェアテスト・シーズンIII
G*におけるソフトウェアテスト・シーズンIIIG*におけるソフトウェアテスト・シーズンIII
G*におけるソフトウェアテスト・シーズンIII
 
Hear no evil, see no evil, patch no evil: Or, how to monkey-patch safely.
Hear no evil, see no evil, patch no evil: Or, how to monkey-patch safely.Hear no evil, see no evil, patch no evil: Or, how to monkey-patch safely.
Hear no evil, see no evil, patch no evil: Or, how to monkey-patch safely.
 
Building unit tests correctly
Building unit tests correctlyBuilding unit tests correctly
Building unit tests correctly
 
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
 
Effective testing with pytest
Effective testing with pytestEffective testing with pytest
Effective testing with pytest
 
Stubる - Mockingjayを使ったHTTPクライアントのテスト -
Stubる - Mockingjayを使ったHTTPクライアントのテスト -Stubる - Mockingjayを使ったHTTPクライアントのテスト -
Stubる - Mockingjayを使ったHTTPクライアントのテスト -
 
Jasmine - why JS tests don't smell fishy
Jasmine - why JS tests don't smell fishyJasmine - why JS tests don't smell fishy
Jasmine - why JS tests don't smell fishy
 
Advance Java Programs skeleton
Advance Java Programs skeletonAdvance Java Programs skeleton
Advance Java Programs skeleton
 
Ad java prac sol set
Ad java prac sol setAd java prac sol set
Ad java prac sol set
 
Migrating to JUnit 5
Migrating to JUnit 5Migrating to JUnit 5
Migrating to JUnit 5
 
Keep your repo clean
Keep your repo cleanKeep your repo clean
Keep your repo clean
 
Enhanced Web Service Testing: A Better Mock Structure
Enhanced Web Service Testing: A Better Mock StructureEnhanced Web Service Testing: A Better Mock Structure
Enhanced Web Service Testing: A Better Mock Structure
 
Programming with Python and PostgreSQL
Programming with Python and PostgreSQLProgramming with Python and PostgreSQL
Programming with Python and PostgreSQL
 

Destacado

5050 dev nation
5050 dev nation5050 dev nation
5050 dev nationArun Gupta
 
JavaOne 2016 - Reactive Microservices with Java and Java EE
JavaOne 2016 - Reactive Microservices with Java and Java EEJavaOne 2016 - Reactive Microservices with Java and Java EE
JavaOne 2016 - Reactive Microservices with Java and Java EERodrigo Cândido da Silva
 
Microservices Technology Stack
Microservices Technology StackMicroservices Technology Stack
Microservices Technology StackEberhard Wolff
 
Microservices + Oracle: A Bright Future
Microservices + Oracle: A Bright FutureMicroservices + Oracle: A Bright Future
Microservices + Oracle: A Bright FutureKelly Goetsch
 
0708 Usability Test Methodes
0708 Usability Test Methodes0708 Usability Test Methodes
0708 Usability Test MethodesHans Kemp
 
Zappos - Connect 09 - 5-13-09
Zappos - Connect 09 - 5-13-09Zappos - Connect 09 - 5-13-09
Zappos - Connect 09 - 5-13-09zappos
 
Iad2 0910 Q1 Hoorcollege 1
Iad2 0910 Q1 Hoorcollege 1Iad2 0910 Q1 Hoorcollege 1
Iad2 0910 Q1 Hoorcollege 1Hans Kemp
 
Brainification van marketing: wat doen we écht met redactionele en commerciël...
Brainification van marketing: wat doen we écht met redactionele en commerciël...Brainification van marketing: wat doen we écht met redactionele en commerciël...
Brainification van marketing: wat doen we écht met redactionele en commerciël...Sanoma Netherlands
 
Health Sciences Libraries
Health Sciences LibrariesHealth Sciences Libraries
Health Sciences LibrariesJoseph Yap
 
Gardeners Not Gate Keepers
Gardeners Not Gate KeepersGardeners Not Gate Keepers
Gardeners Not Gate Keeperscalevans
 
The bambino tour
The bambino tourThe bambino tour
The bambino tourelenargy
 
0708 Ontwerpproces en beroepsproducten
0708 Ontwerpproces en beroepsproducten0708 Ontwerpproces en beroepsproducten
0708 Ontwerpproces en beroepsproductenHans Kemp
 
Legal aspects of data gathering and information exchange
Legal aspects of data gathering and information exchangeLegal aspects of data gathering and information exchange
Legal aspects of data gathering and information exchangeStevenSegaert
 

Destacado (20)

Codemotion 2015 spock_workshop
Codemotion 2015 spock_workshopCodemotion 2015 spock_workshop
Codemotion 2015 spock_workshop
 
Java8.part2
Java8.part2Java8.part2
Java8.part2
 
5050 dev nation
5050 dev nation5050 dev nation
5050 dev nation
 
TDD and BDD in Java 8 - what's in it for me?
TDD and BDD in Java 8 - what's in it for me?TDD and BDD in Java 8 - what's in it for me?
TDD and BDD in Java 8 - what's in it for me?
 
Going further with CDI 1.2
Going further with CDI 1.2Going further with CDI 1.2
Going further with CDI 1.2
 
Unit test-using-spock in Grails
Unit test-using-spock in GrailsUnit test-using-spock in Grails
Unit test-using-spock in Grails
 
JavaOne 2016 - Reactive Microservices with Java and Java EE
JavaOne 2016 - Reactive Microservices with Java and Java EEJavaOne 2016 - Reactive Microservices with Java and Java EE
JavaOne 2016 - Reactive Microservices with Java and Java EE
 
BDD Anti-patterns
BDD Anti-patternsBDD Anti-patterns
BDD Anti-patterns
 
Microservices Technology Stack
Microservices Technology StackMicroservices Technology Stack
Microservices Technology Stack
 
Microservices + Oracle: A Bright Future
Microservices + Oracle: A Bright FutureMicroservices + Oracle: A Bright Future
Microservices + Oracle: A Bright Future
 
0708 Usability Test Methodes
0708 Usability Test Methodes0708 Usability Test Methodes
0708 Usability Test Methodes
 
Zappos - Connect 09 - 5-13-09
Zappos - Connect 09 - 5-13-09Zappos - Connect 09 - 5-13-09
Zappos - Connect 09 - 5-13-09
 
Iad2 0910 Q1 Hoorcollege 1
Iad2 0910 Q1 Hoorcollege 1Iad2 0910 Q1 Hoorcollege 1
Iad2 0910 Q1 Hoorcollege 1
 
Brainification van marketing: wat doen we écht met redactionele en commerciël...
Brainification van marketing: wat doen we écht met redactionele en commerciël...Brainification van marketing: wat doen we écht met redactionele en commerciël...
Brainification van marketing: wat doen we écht met redactionele en commerciël...
 
Health Sciences Libraries
Health Sciences LibrariesHealth Sciences Libraries
Health Sciences Libraries
 
Gardeners Not Gate Keepers
Gardeners Not Gate KeepersGardeners Not Gate Keepers
Gardeners Not Gate Keepers
 
The bambino tour
The bambino tourThe bambino tour
The bambino tour
 
0708 Ontwerpproces en beroepsproducten
0708 Ontwerpproces en beroepsproducten0708 Ontwerpproces en beroepsproducten
0708 Ontwerpproces en beroepsproducten
 
Actividad 3
Actividad 3Actividad 3
Actividad 3
 
Legal aspects of data gathering and information exchange
Legal aspects of data gathering and information exchangeLegal aspects of data gathering and information exchange
Legal aspects of data gathering and information exchange
 

Similar a Spock: Test Well and Prosper

Everything is Permitted: Extending Built-ins
Everything is Permitted: Extending Built-insEverything is Permitted: Extending Built-ins
Everything is Permitted: Extending Built-insAndrew Dupont
 
Cool Jvm Tools to Help you Test - Aylesbury Testers Version
Cool Jvm Tools to Help you Test - Aylesbury Testers VersionCool Jvm Tools to Help you Test - Aylesbury Testers Version
Cool Jvm Tools to Help you Test - Aylesbury Testers VersionSchalk Cronjé
 
Csmr2012 bettenburg presentation
Csmr2012 bettenburg presentationCsmr2012 bettenburg presentation
Csmr2012 bettenburg presentationSAIL_QU
 
Introduction to clojure
Introduction to clojureIntroduction to clojure
Introduction to clojureAbbas Raza
 
Getting started with Clojure
Getting started with ClojureGetting started with Clojure
Getting started with ClojureJohn Stevenson
 
Cool JVM Tools to Help You Test
Cool JVM Tools to Help You TestCool JVM Tools to Help You Test
Cool JVM Tools to Help You TestSchalk Cronjé
 
Spock Framework - Slidecast
Spock Framework - SlidecastSpock Framework - Slidecast
Spock Framework - SlidecastDaniel Kolman
 
Pocket Talk; Spock framework
Pocket Talk; Spock frameworkPocket Talk; Spock framework
Pocket Talk; Spock frameworkInfoway
 
Atlassian Groovy Plugins
Atlassian Groovy PluginsAtlassian Groovy Plugins
Atlassian Groovy PluginsPaul King
 
BDD - Behavior Driven Development Webapps mit Groovy Spock und Geb
BDD - Behavior Driven Development Webapps mit Groovy Spock und GebBDD - Behavior Driven Development Webapps mit Groovy Spock und Geb
BDD - Behavior Driven Development Webapps mit Groovy Spock und GebChristian Baranowski
 
55 new things in Java 7 - Devoxx France
55 new things in Java 7 - Devoxx France55 new things in Java 7 - Devoxx France
55 new things in Java 7 - Devoxx FranceDavid Delabassee
 
Grails unit testing
Grails unit testingGrails unit testing
Grails unit testingpleeps
 
Node.js System: The Landing
Node.js System: The LandingNode.js System: The Landing
Node.js System: The LandingHaci Murat Yaman
 
React Native One Day
React Native One DayReact Native One Day
React Native One DayTroy Miles
 
Whitebox testing of Spring Boot applications
Whitebox testing of Spring Boot applicationsWhitebox testing of Spring Boot applications
Whitebox testing of Spring Boot applicationsYura Nosenko
 
Oscon Java Testing on the Fast Lane
Oscon Java Testing on the Fast LaneOscon Java Testing on the Fast Lane
Oscon Java Testing on the Fast LaneAndres Almiray
 

Similar a Spock: Test Well and Prosper (20)

Spock
SpockSpock
Spock
 
Everything is Permitted: Extending Built-ins
Everything is Permitted: Extending Built-insEverything is Permitted: Extending Built-ins
Everything is Permitted: Extending Built-ins
 
Cool Jvm Tools to Help you Test - Aylesbury Testers Version
Cool Jvm Tools to Help you Test - Aylesbury Testers VersionCool Jvm Tools to Help you Test - Aylesbury Testers Version
Cool Jvm Tools to Help you Test - Aylesbury Testers Version
 
Csmr2012 bettenburg presentation
Csmr2012 bettenburg presentationCsmr2012 bettenburg presentation
Csmr2012 bettenburg presentation
 
Spock
SpockSpock
Spock
 
Unit testing
Unit testingUnit testing
Unit testing
 
Introduction to clojure
Introduction to clojureIntroduction to clojure
Introduction to clojure
 
Getting started with Clojure
Getting started with ClojureGetting started with Clojure
Getting started with Clojure
 
Cool JVM Tools to Help You Test
Cool JVM Tools to Help You TestCool JVM Tools to Help You Test
Cool JVM Tools to Help You Test
 
Spock Framework - Slidecast
Spock Framework - SlidecastSpock Framework - Slidecast
Spock Framework - Slidecast
 
Pocket Talk; Spock framework
Pocket Talk; Spock frameworkPocket Talk; Spock framework
Pocket Talk; Spock framework
 
Atlassian Groovy Plugins
Atlassian Groovy PluginsAtlassian Groovy Plugins
Atlassian Groovy Plugins
 
BDD - Behavior Driven Development Webapps mit Groovy Spock und Geb
BDD - Behavior Driven Development Webapps mit Groovy Spock und GebBDD - Behavior Driven Development Webapps mit Groovy Spock und Geb
BDD - Behavior Driven Development Webapps mit Groovy Spock und Geb
 
55 new things in Java 7 - Devoxx France
55 new things in Java 7 - Devoxx France55 new things in Java 7 - Devoxx France
55 new things in Java 7 - Devoxx France
 
55 New Features in Java 7
55 New Features in Java 755 New Features in Java 7
55 New Features in Java 7
 
Grails unit testing
Grails unit testingGrails unit testing
Grails unit testing
 
Node.js System: The Landing
Node.js System: The LandingNode.js System: The Landing
Node.js System: The Landing
 
React Native One Day
React Native One DayReact Native One Day
React Native One Day
 
Whitebox testing of Spring Boot applications
Whitebox testing of Spring Boot applicationsWhitebox testing of Spring Boot applications
Whitebox testing of Spring Boot applications
 
Oscon Java Testing on the Fast Lane
Oscon Java Testing on the Fast LaneOscon Java Testing on the Fast Lane
Oscon Java Testing on the Fast Lane
 

Spock: Test Well and Prosper