【问题标题】:Is it possible to get the number of call in Spock是否有可能在Spock中获得电话号码
【发布时间】:2018-01-18 16:50:44
【问题描述】:

是否可以在Spock中获取mocked方法的调用次数?我想测试该方法是否被调用了特定次数,但是每秒返回的值应该不同。下面的伪代码应该更具体地说明我想要什么:

void "My idea of a test" {
    when:
       ...
    then:
        10 * someService(_) >> {
             return theNumberOfTheCall % 2 ? SOME_VALUE : null // theNumberOfTheCall should illustrate my purpose
        }
// so the service will return [null, SOME_VALUE, null, SOME_VALUE, null ...]
}

【问题讨论】:

    标签: groovy spock


    【解决方案1】:

    可以使用链接来完成:

    10 * someService(_) >>> (1..10).collect {
           it % 2 ? SOME_VALUE : null
    }
    

    【讨论】:

      【解决方案2】:

      Spock 本身不会将调用次数传递给模拟方法,但您使用AtomicInteger 来增加测试方法中定义的计数器。考虑以下简单示例:

      import spock.lang.Specification    
      import java.util.concurrent.atomic.AtomicInteger
      
      class InvocationCounterSpec extends Specification {
      
          def "should return different value depending on invocation counter"() {
              setup:
              final AtomicInteger counter = new AtomicInteger(0)
              final SomeService someService = Mock(SomeService)
              final SomeClass someClass = new SomeClass(someService)
      
              when:
              someClass.run()
      
              then:
              10 * someService.someMethod() >> {
                  return counter.getAndIncrement() % 2 ? "SOME_VALUE" : null
              }
      
          }
      
          static interface SomeService {
              def someMethod()
          }
      
          static class SomeClass {
              private final SomeService someService
      
              SomeClass(SomeService someService) {
                  this.someService = someService
              }
      
              void run() {
                  (0..<10).each {
                      def value = someService.someMethod()
                      println "someService.someMethod() returned ${value}"
                  }
              }
          }
      }
      

      在这个例子中,someClass.run() 方法调用了模拟的someService.someMethod() 10 次。我们使用为我们计算调用次数的计数器存根 someService.someMethod() 返回值。如果您运行此测试,您将看到以下输出:

      someService.someMethod() returned null
      someService.someMethod() returned SOME_VALUE
      someService.someMethod() returned null
      someService.someMethod() returned SOME_VALUE
      someService.someMethod() returned null
      someService.someMethod() returned SOME_VALUE
      someService.someMethod() returned null
      someService.someMethod() returned SOME_VALUE
      someService.someMethod() returned null
      someService.someMethod() returned SOME_VALUE
      

      希望对你有帮助。

      【讨论】:

        猜你喜欢
        • 2016-08-07
        • 2012-10-27
        • 2016-06-17
        • 2011-08-28
        • 1970-01-01
        • 1970-01-01
        • 2016-01-03
        • 1970-01-01
        • 2011-08-11
        相关资源
        最近更新 更多