java - Spock:在 stub 中返回输入参数

标签 java groovy mocking spock

给定一个带有参数的方法在 Java 中,例如

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

当 stub /模拟 foo 时,我如何告诉它接受任何参数并返回它? (时髦)

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

如您所见,我传递了身份函数。但是我不知道该传递什么作为参数。 _ 不起作用,因为它是一个 ArrayList,因此不是 Bar

类型

最佳答案

您可以通过以下方式 stub Foo 类:

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

这里是完整的例子:

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
    }
}

关于java - Spock:在 stub 中返回输入参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46607848/

相关文章:

java - EasyMock:andAnswer() 与 andDelegateTo()

Java 更改 ArrayList<Double> 中 double 型的格式

java - 找不到资源包异常

java - 序列化反序列化对象 EOFException

groovy - 在 Netbeans 中运行 fork 的 groovyc 时出错

regex - 如何否定Groovy Match运算符?

java - addAll 如何在 android 列表适配器中工作?

XmlSlurper - 列出 xhtml 文档的文本和常规节点

mocking - 在移动原生应用测试中 : How to mock backend when using Appium?

组件级别的 Angular 模拟服务