Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spock: Return input parameter in Stubs

Given an method with a parameter in Java, e.g.

public class Foo {
   public Bar theBar(Bar bar) { /*... */ }   
}

When stubbing/ mocking foo, how do I tell it to accept any argument and return it? (Groovy)

def fooStub = Stub(Foo) {
  theBar(/*what to pass here*/) >> { x -> x }
}

As you can see I passed the identity function. However I do not know what to pass as argument. _ does not work because it is an ArrayList and thus not of type Bar

like image 825
user3001 Avatar asked Oct 06 '17 14:10

user3001


1 Answers

You can stub Foo class in following way:

Foo foo = Stub(Foo)
foo.theBar(_ as Bar) >> { Bar bar -> bar }

And here is full example:

import groovy.transform.Immutable
import spock.lang.Specification

class StubbingSpec extends Specification {

    def "stub that returns passed parameter"() {
        given:
        Foo foo = Stub(Foo)
        foo.theBar(_ as Bar) >> { Bar bar -> bar }

        when:
        def result = foo.theBar(new Bar(10))

        then:
        result.id == 10
    }

    static class Foo {
        Bar theBar(Bar bar) {
            return null
        }
    }

    @Immutable
    static class Bar {
        Integer id
    }
}
like image 82
Szymon Stepniak Avatar answered Oct 21 '22 13:10

Szymon Stepniak