2017-10-06 89 views
1

给定一个参数为的Java(例如,Spock:存根中的返回输入参数

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

当磕碰/ foo的嘲讽,我怎么告诉它接受任何参数和返回值呢? (Groovy的

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

正如你可以看到我通过了身份功能。但是我不知道要传递什么参数。 _不起作用,因为它是ArrayList,因此不是Bar

+0

你有'@ CompileStatic'或'@ TypeChecked'你的规范呢?你可以发布你的整个代码,没有理由不应该使用'_'。 –

回答

0

我不确定你的意思。 _是正确的事情通过。你为什么认为这是一个ArrayList?这是类型Object,可用于任何事情。

+0

这意味着在Java中,它有错误的类型(不是'Bar'),对吧? – user3001

+0

那么? Spock基于Groovy,你不能在Java中使用Spock。 – Vampire

2

您可以按以下方式存根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 
    } 
} 
+0

您是否尝试过使用'Foo'和'Bar'作为Java类? – user3001

+0

@ user3001是的,当'Foo'和'Bar'是Java类时,它的工作原理完全相同,只是测试了这个例子并得到了相同的结果。 –