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

Unit testing 如何使用Spock mocks有效地模拟流畅的界面?,unit-testing,groovy,spock,Unit Testing,Groovy,Spock,我想用mock模拟一些流畅的界面,mock基本上是一个邮件生成器: this.builder() .from(from) .to(to) .cc(cc) .bcc(bcc) .template(templateId, templateParameter) .send(); 使用Spock模拟时,需要进行大量如下设置: def builder = Moc

我想用mock模拟一些流畅的界面,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 "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
}
等等。当您想测试与mock的某些交互时,它会变得更加麻烦,这取决于用例。所以我这里基本上有两个问题:

  • 有没有一种方法可以组合模拟规则,这样我就可以用一种可以在每个测试用例上重用的方法一次性设置fluent接口,然后为每个测试用例指定额外的规则
  • 有没有一种方法可以指定用较少的代码模拟流畅的界面,例如:

    def生成器=模拟(生成器) 建筑商。/(从|到|抄送|密件抄送|模板)/(*)>>建筑商

    或者类似于莫基托的深桩的东西(参见)


  • 您可以这样做:

    def builder = Mock(Builder)
    builder.from(_) >> builder
    builder.to(_) >> builder 
    
    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模拟框架工作方式的固有特点。这与JMock、EasyMock等使用的方法相同。只有Mockito使用了不同的方法,这还有其他缺点。