我想用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 构建器 = 模拟(构建器) 构建器。/(from|to|cc|bcc|template)/(*) >> 构建器
或相当于 Mockito 的 Deep Stubs 的东西(请参阅 http://docs.mockito.googlecode.com/hg/org/mockito/Mockito.html#RETURNS_DEEP_STUBS)
你可以这样做:
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
}
在现代 Spock 中,可以使用默认响应提供者配置模拟:
Builder builder = Mock(defaultResponse: EmptyOrDummyResponse.INSTANCE)
EmptyOrDummyResponse
是Spock框架本身提供的类。
所以完整的用法示例是:
def "stubbing and mocking a builder"() {
given:
Builder builder = Mock(defaultResponse: EmptyOrDummyResponse.INSTANCE)
when:
// exercise code that uses builder
then:
// interactions in then-block override any other interactions
1 * builder.to("fred") >> builder
}