Spock Web Console

subscribe to the feed Subscribe
Spok Quick Primer (via #spockwebconsole)
tweet this script Tweet

Spok Quick Primer

Published 7 months ago by Kshitij Limaye with tags primer quick-start guide
Actions  ➤ Edit In Console Back To Console Show/Hide Line Numbers View Recent Scripts
import spock.lang.*

// Hit 'Run Script' below
class MyFirstSpec extends Specification {
    @Shared  
    def commonString = "abcd"
    //run once for the entire spec.
    def setupSpec() {
        //we could have initialized commonString here as well
        //can only access fields annotated by @Shared
    }
    def setup() {
        //run once for every feature method
    }
    
    def initializedEveryTimeForEachMethod = "efgh"
    static final PI = 3.14
  def "let's try this!"() {    
    expect:
    initializedEveryTimeForEachMethod == "efgh"
    Math.min(commonString.length(), 3) == 3
  }
  def "another test"() {
    expect:
        commonString.length() == initializedEveryTimeForEachMethod.length()
  }
  def "add to stack test"() {
    setup:
        def stack = new Stack()
        def item = "firstItem"
    when:
        stack.push(item)
    then:
        !stack.empty()
        stack.size() == 1
        stack.peek() == item
  }
  def "pop from stack test"() {
    setup:
        def stack = new Stack()
    when:
        stack.pop()
    then:
        thrown(EmptyStackException)
  }
  def "stack test with with:"() {
    setup:
        def stack = new Stack()
    when:
        stack.push(1)
    then:
        with(stack) {
            !stack.empty()
            stack.size() == 1
            stack.peek() == 1
        }
  }
  def "hashmap accepts a null key"() {
    //given: is an alias for setup:
    given:
        def hashmap = new HashMap()
    when:
        hashmap.put(null,"null key")
    then:
        notThrown(NullPointerException)
  }
  //use expect to describe purely functions instead of using when-then
  def "test a pure function"() {
    setup:
        def list = ["1","a","b","c"]
    expect:
        "abcd".length() == 4
        list.any { it == "1" }
        
  }
  @Unroll
  def "test the where block"() {
    expect:
        Math.max(a,b) == c
    where:
        a << [5,3]
        b << [1,9]
        c << [5,9]
  }
}