如何使用Spock模拟有效地模拟流畅的界面?

时间:2013-05-27 11:50:42

标签: unit-testing groovy spock

我想用mock来模拟一些流畅的界面,这基本上是一个邮件构建器:

this.builder()
            .from(from)
            .to(to)
            .cc(cc)
            .bcc(bcc)
            .template(templateId, templateParameter)
            .send();

使用Spock进行模拟时,需要进行大量设置:

def builder = Mock(Builder)
builder.from(_) >> builder
builder.to(_) >> builder 

等。当您想要测试与模拟的某些交互时,它会变得更加麻烦,具体取决于用例。所以我在这里基本上有两个问题:

  1. 有没有办法组合模拟规则,这样我就可以在一个方法中对流畅的接口进行一般的一次性设置,我可以在每个测试用例中重复使用,然后为每个测试用例指定其他规则?
  2. 有没有办法用较少的代码指定一个流畅的界面的模拟,例如类似的东西:

    def builder = Mock(Builder) builder./(from|to|cc | bcc | template)/(*)>>助洗剂

    或等同于Mockito的Deep Stubs(见http://docs.mockito.googlecode.com/hg/org/mockito/Mockito.html#RETURNS_DEEP_STUBS

1 个答案:

答案 0 :(得分:15)

您可以这样做:

def "stubbing and mocking a builder"() {
    def builder = Mock(Builder)
    // could also put this into a setup method
    builder./from|to|cc|bcc|template|send/(*_) >> builder

    when:
    // exercise code that uses builder

    then:
    // interactions in then-block override any other interactions
    // note that you have to repeat the stubbing
    1 * builder.to("fred") >> builder
}