我想用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
等。当您想要测试与模拟的某些交互时,它会变得更加麻烦,具体取决于用例。所以我在这里基本上有两个问题:
有没有办法用较少的代码指定一个流畅的界面的模拟,例如类似的东西:
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)
答案 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
}