Skip to content

Instantly share code, notes, and snippets.

@adrianmilne
Created May 11, 2018 10:37
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save adrianmilne/8a8cace103ab6a8fd754640876d60edd to your computer and use it in GitHub Desktop.
Save adrianmilne/8a8cace103ab6a8fd754640876d60edd to your computer and use it in GitHub Desktop.
Spock Argument Constraint and Argument Capture Examples
import spock.lang.Specification
/**
* Unit tests for {@link Controller}
*/
class ControllerTest extends Specification {
private static final String USERNAME = 'Duggie'
private static final String EMAIL = 'Duggie@test.com'
/**
* Long hand example of using an Object Argument Constraint in Spock.
*/
def 'test_register_using_explicit_argument_constraint'(){
given: 'a mocked service'
def mockService = Mock(Service)
def controller = new Controller()
controller.service = mockService
when: 'controller registers a new user'
controller.register(USERNAME, EMAIL)
then: 'service is called with expected parameters'
1 * mockService.register({User u -> u.name == USERNAME && u.email == EMAIL})
}
/**
* Short hand version of code above, using implicit 'it'.
*/
def 'test_register_using_implicit_argument_constraint'(){
given: 'a mocked service'
def mockService = Mock(Service)
def controller = new Controller()
controller.service = mockService
when: 'controller registers a new user'
controller.register(USERNAME, EMAIL)
then: 'service is called with expected parameters'
1 * mockService.register({it.name == USERNAME && it.email == EMAIL})
}
/**
* Using Argument Capture approach - this is not as neat for verifying contents of arguments
* (which is what argument constraints are for), but it does also allow you to manipulate those
* arguments if you need to
*/
def 'test_register_using_argument_capture'(){
given: 'a mocked service'
def mockService = Mock(Service)
def test
def controller = new Controller()
controller.service = mockService
when: 'controller registers a new user'
controller.register(USERNAME, EMAIL)
then: 'service is called with expected parameters'
1 * mockService.register(_ as User) >> {arguments ->
assert arguments[0].name == USERNAME && arguments[0].email == EMAIL
// Note with an argument capture - as well as verifying input
// you can also do other things - (if you need to), e.g.:
arguments[0].name = 'I changed the name in the test!'
test = arguments[0].name
}
assert test == 'I changed the name in the test!'
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment