Spock: Return input parameter in Stubs
Asked Answered
D

2

9

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

Digged answered 6/10, 2017 at 14:16 Comment(2)
Do you have @CompileStatic or @TypeChecked on your spec? could you post your whole code, there is no reason why _ shouldn't work.Dyl
Just ran into the same setup and situation. Trying to stub a Java class from Spock + Groovy and I only want to return the method's input, no more no less. Since I have no idea what's going on I simply leave my solution as a comment and I'd appreciate if someone could enlighten me. It seems the x input before the arrow is actually the entire arguments list of the method call? Doing the following solves the problem: theBar(_) >> { args -> args.get(0) }. But why is that necessary? How to express this correctly without any hacks?Chessy
A
11

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
    }
}
Audy answered 6/10, 2017 at 14:32 Comment(2)
Did you try the same with Foo and Bar being Java classes?Digged
@Digged Yes, it works exactly the same when Foo and Bar are Java classes, just tested this example and got same result.Audy
S
0

I'm not sure what you mean. _ is the right thing to pass. Why do you think it is an ArrayList? It is of type Object and can be used for anything.

Shilohshim answered 6/10, 2017 at 14:25 Comment(2)
That means that in Java, it has the wrong type (not Bar), right?Digged
So? Spock is Groovy based, you cannot use Spock with Java.Shilohshim

© 2022 - 2024 — McMap. All rights reserved.