Search code examples
spock

how to get capture all arguments of mock


I got mock:

MyService myServiceMock=Mock()

In my test I'm using it like this:

myCollection.stream()
    .map(myServiceMock::myMethod)
    ...

How I can get all arguments passed to myServiceMock in all invocations?


Solution

  • interface MyService {
        def myMethod(String s)
    }
    
    def foo() {
        given:
            def capturedArguments = []
            MyService myServiceMock = Mock {
                myMethod(_) >> { capturedArguments << it.first() }
            }
            def myCollection = ['a', 'b']
    
        when:
            myCollection
                    .stream()
                    .map(myServiceMock::myMethod)
                    .each { }
    
        then:
            capturedArguments ==~ ['a', 'b']
    }