Spock: Test Well and Prosper

39
Spock I have been, and always shall be, your friendly testing framework

description

Demonstrates the basics of the Spock framework for unit testing Java and Groovy applications

Transcript of Spock: Test Well and Prosper

Page 1: Spock: Test Well and Prosper

SpockI have been, and always shall be, your

friendly testing framework

Page 3: Spock: Test Well and Prosper

Testing frameworkWritten in Groovy

A logical framework for enterprise testing

Combination ofSpecification + Mock

What is Spock?

Page 4: Spock: Test Well and Prosper

Spock home pagehttp://spockframework.org

redirects to http://code.google.com/p/spock

Githubhttps://github.com/spockframework/spock

The Search for Spock

Page 5: Spock: Test Well and Prosper

Extend spock.lang.Specification

class MySpec extends Specification

Create a Spock test

Page 6: Spock: Test Well and Prosper

Demo: Palindrome Checker

Simple Specification

Page 7: Spock: Test Well and Prosper

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

Fixture Methods

Page 8: Spock: Test Well and Prosper

Test methodsdef "descriptive name"() {

// blocks}

Feature Methods

Page 9: Spock: Test Well and Prosper

setup: cleanup:given:

when:Stimulus

then:Response, booleans are checked

expect: where:

Blocks

Page 10: Spock: Test Well and Prosper

when:Contents are arbitrary

then:conditionsexceptionsinteractions (mocks described below)

Always occur together

when: and then:

Page 11: Spock: Test Well and Prosper

Sweet method in Specification class

expression value beforewhere block

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

old Method what they thought old Kirk would look like

what he actually looks like

Page 12: Spock: Test Well and Prosper

Annotation for shared objectsNote: instance fields are not shared

@Shared res = new VeryExpensiveResource()

@Shared sql = Sql.newInstance(...)

@Shared

Page 13: Spock: Test Well and Prosper

Demo: Library Computer

@Shared

Page 14: Spock: Test Well and Prosper

thrown() and notThrown()

then:thrown(SqlException)

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

Can do work after catching exception

Exceptions are exceptions evil or just goatees?

Page 15: Spock: Test Well and Prosper

Tests that iterate through dataUse where: clause

expect: name.size() == length

where:[name,length] << [['Kirk',4],['Spock',5]]

Parameterized feature methods

Page 16: Spock: Test Well and Prosper

where: clause supports data tables

expect: name.size() == lengthwhere: name | length 'Kirk' | 4'Spock' | 5'McCoy' | 5

Data Table

Shouldn't Data run on Android?

Page 17: Spock: Test Well and Prosper

Supports anything Groovy can iterate over

expect: x + y == zwhere:[x,y,z] << sql.rows('select x,y,z from ...')

where: clause

Page 18: Spock: Test Well and Prosper

Display separate messagefor each row of data

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

Spock 0.6+:@Unrolldef "my test #var ..."() { ... }

@Unroll

Page 19: Spock: Test Well and Prosper

Demos:Hello, Spock!DataDrivenDatabaseDrivenStadiumLocationsSpec

Data Specs

Page 20: Spock: Test Well and Prosper

Working with Mock objects

Interactions

interaction

NO KILL I

Page 21: Spock: Test Well and Prosper

Two syntax options:def items = Mock(List)

List items = Mock()

Can mock interfaces with standard libsMock classes with CGLIB

Creating Mocks

Page 22: Spock: Test Well and Prosper

Setting Expectations

Use >> operatorlist.get(0) >> 'data'

Page 23: Spock: Test Well and Prosper

Global:Defined outside then: blockValid to end of feature method

Local:Defined inside then: blockValid inside preceding when: block

Global vs Local

Page 24: Spock: Test Well and Prosper

No cardinalityMust have return value

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

Optional

Page 25: Spock: Test Well and Prosper

Must have cardinalityMay have return value

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

then:3 * list.size()

Required

Page 26: Spock: Test Well and Prosper

Ranges with wildcardWildcard is _ (underscore)

3 * list.size() // 3 times(3.._) * list.size() // 3 or more(_..3) * list.size() // up to 3

Cardinalities

Page 27: Spock: Test Well and Prosper

RegexAny set method with one argpojo./set.*/(_)

Nulls, not nullpojo.method(!null)

All sorts of constraints

Page 28: Spock: Test Well and Prosper

as Operatordir.listFiles(_ as FileFilter)

Closurescount.increment { it ==~ /a*b/ }

All sorts of constraints

Page 29: Spock: Test Well and Prosper

Use multiple then blocks

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

then: 1*collaborator.method1()then: 1*collaborator.method2()

}

Testing Invocation Order

Page 30: Spock: Test Well and Prosper

Interactions

Demos:PublisherSubscriberTribbleSpec

Page 31: Spock: Test Well and Prosper

@Timeout

@Ignore

@IgnoreRest

@FailsWith

Extensions

Page 32: Spock: Test Well and Prosper

Test fails with expected exception

@FailsWith(TooFewInvocationsError)def "required interaction"() {

def m = Mock(List)2 * m.get(_) >> "foo"expect: m.get(3) == "foo"

}

@FailsWith

Page 33: Spock: Test Well and Prosper

Parametersvalue=ExpectedExceptionOrErrorreason="reason for failure"

@FailsWith

Page 34: Spock: Test Well and Prosper

@IgnoreDon't run a particular test or test classOptional value = reason

@IgnoreRestDon't run any OTHER tests

@Ignore and @IgnoreRest

Page 35: Spock: Test Well and Prosper

Method in Specification classTakes closure argument

def 'use interaction block'() {when: obj.method()then:interaction {

// do whatever}

}

interaction block

Page 36: Spock: Test Well and Prosper

BDD

Behavior Driven DevelopmentEach block accepts string descriptionJust 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"

}

Page 37: Spock: Test Well and Prosper

Like most modern open source projects

Documentation can be thin or outdated

Tests are excellent

See "smoke" tests in source

Spock's Own Tests

Page 38: Spock: Test Well and Prosper

http://github.com/spockframework/spockhttp://code.google.com/p/spockhttp://spockframework.orghttp://meet.spockframework.orghttp://groups.google.com/group/spockframework?pli=1

Source code for examples is from1. spock-example project

https://github.com/spockframework/spock-example2. my GitHub repo

https://github.com/kousen/Spock-NFJS-Article

Links

Page 39: Spock: Test Well and Prosper

Please complete your session evals

Session Evals