16

我想用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)/(*) >> builder

    或相当于 Mockito 的 Deep Stubs 的东西(请参阅http://docs.mockito.googlecode.com/hg/org/mockito/Mockito.html#RETURNS_DEEP_STUBS

4

1 回答 1

18

你可以这样做:

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
}
于 2013-05-28T10:17:05.440 回答