簡體   English   中英

Spock:在Stubs中返回輸入參數

[英]Spock: Return input parameter in Stubs

給出一個帶有Java參數的方法,例如

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

當存根/模擬foo時,如何告訴它接受任何參數並返回它? Groovy

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

如你所見,我通過了身份功能。 但是我不知道要傳遞什么作為參數。 _不起作用,因為它是一個ArrayList ,因此不是Bar類型

您可以通過以下方式存根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
    }
}

我不確定你是什么意思。 _是正確的事情。 為什么你認為它是一個ArrayList 它是Object類型,可以用於任何事情。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM