Spock Web Console

subscribe to the feed Subscribe
MockExamplev2 (via #spockwebconsole)
tweet this script Tweet

MockExamplev2

Published 3 months ago by lajos with tags spock
Actions  ➤ Edit In Console Back To Console Show/Hide Line Numbers View Recent Scripts
import spock.lang.*

class FooControllerSpec extends Specification {
  
  def "mock example"() {
    given: "the collaborating service is mocked"
    def mockFooService = Mock(FooService)
    
    and: "having a real controller using the mocked service"
    def controller = new FooController()
    controller.fooService = mockFooService

    when: "the controller action is called"
    def result = controller.doSomething()

    then: "the mock can be used to validate cardinality and parameters"
    1 * mockFooService.doSomething("with me")

    and: "the mock service returns the default 'zero value' of 'null'"
    result == null
  }

  interface FooService {
    String doSomething(String name)
  }

  class FooController {
    FooService fooService
    def doSomething() {
      return fooService.doSomething("with me")
    }
  }
}