MSSE SENG 5199

Course Materials for the MSSE Web Application Development Course

autoscale: true theme: Next, 3

Spock Testing Framework


What is Spock?


Why Spock?


Simple Rules

def "pop items from stack"() { ... }

Feature Methods


Blocks


Setup Blocks

setup:
def stack = new Stack()
def elem = 'push me'

When and Then Blocks

when:
stack.push(value)

then:
stack.size() == originalSize+1

Conditions


Interactions

when:
publisher.fire('event')

then:
1 * subscriber1.receive('event')
1 * subscriber2.receive('event')

Mocks

def s = Mock(TypeToBeMocked)

Cardinalities

n * subscriber.receive(event)      // exactly n times
(n.._) * subscriber.receive(event) // at least n times
(_..n) * subscriber.receive(event) // at most n times

Argument Constraints


Return values

subscriber.isAlive() >> true  
subscriber.isAlive() >>> [true, false, true]
subscriber.isAlive() >> { random.nextBoolean() }

Mock Example

setup:
def event = new Event()
def subscriber = Mock(Subscriber)
subscriber.isAlive() >> true // global interaction

when:
publisher.send(event)

then:
1 * subscriber.receive(event) // local interaction

Full Example

class MySpec extends Specification {

  def 'simple test of something silly'() {
    setup:
    def input = 10

    when:
    def result = service.add(input)

    then:
    result == input + 10
  }
}

Testing Expected Exceptions

def 'bad things happen'() {
  when:
  service.provide(null)

  then:
  thrown(IllegalArgumentException)
}

Data-driven Tests


Data-driven Example

@Unroll('#description')
  def 'list size matches'() {
    given:
    def list = []

    when:
    for (int i = 1; i <= count; i++) {
      list << [creationIndex: count]
    }

    then:
    list.size() == expectedReturned

    where:
    description  | count | expectedReturned
    'Zero'       | 0     | 0
    'Two'        | 2     | 2
    'Ten'        | 10    | 10
  }

Fixture Methods


Helper Methods


Optional Block Descriptions

given: 'an empty bank account'
// ...
when: 'the account is credited $10'
// ...
then: "the account's balance ins $10"
// ...

Spock Extensions


Spock with Spring Boot

Add the spock-spring library to your project

testCompile('org.spockframework:spock-spring:1.1-groovy-2.4-rc-3')

testCompile("org.spockframework:spock-core:${groovyVersion}") {
    exclude module: 'groovy-all'
  }

Spring Annotations for testing (class level)

@ContextConfiguration
@DataJpaTest
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)

Try Spock Out

http://meetspock.appspot.com/?id=9001