首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Spock:返回Stubs中的输入参数

Spock:返回Stubs中的输入参数
EN

Stack Overflow用户
提问于 2017-10-06 14:16:17
回答 2查看 7.1K关注 0票数 9

给出了一个具有Java参数的方法。

代码语言:javascript
复制
public class Foo {
   public Bar theBar(Bar bar) { /*... */ }   
}

在固执/嘲笑foo时,我如何告诉它接受任何论点并返回它?(Groovy)

代码语言:javascript
复制
def fooStub = Stub(Foo) {
  theBar(/*what to pass here*/) >> { x -> x }
}

如您所见,我传递了身份函数。不过,作为论据,我不知道该通过什么。_不能工作,因为它是一个ArrayList,因此不属于Bar类型。

EN

回答 2

Stack Overflow用户

发布于 2017-10-06 14:32:12

您可以通过以下方式对Foo类进行存根:

代码语言:javascript
复制
Foo foo = Stub(Foo)
foo.theBar(_ as Bar) >> { Bar bar -> bar }

下面是一个完整的例子:

代码语言:javascript
复制
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
    }
}
票数 10
EN

Stack Overflow用户

发布于 2017-10-06 14:25:46

我不知道你是什么意思。_是正确的通过。你为什么认为它是ArrayList?它是Object型的,可用于任何场合。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/46607848

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档