我想用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)/(*) >> builder
或等同于 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
}
关于unit-testing - 如何使用 Spock 模拟有效地模拟流畅的界面?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16772600/