title: Spock - How to check method invocation count on a Spy object?
body: <p>I'm having tough time get this spock test to work.</p>
  
  <p>I have a Spring repo/DAO class that invokes stored procedures multiple times. I'm trying to write a unit test that validates if the SP is invoked 'x' number of times (3 invocations to createSP() method).</p>
  
  <pre><code>public class PlanConditionRepositoryImpl{
  
      ....
  
      public void write() {
          for (int i=0; i&lt;3; i++) {
              createSP(new ConditionGroup(), new Condition()).call();
          }
      }
  
      protected StoredProcedure&lt;Void&gt; createSP(ConditionGroup planConditionGroup, Condition planCondition) {
          return new StoredProcedure&lt;Void&gt;()
                  .jdbcTemplate(getJdbcTemplate())
                  .schemaName(SCHEMA_NAME);
      }
  }       
  </code></pre>
  
  <p>However the below implementation is not doing that. How do I achieve the invocation count check? Or how do I avoid calling the actual implementation of <code>createSP()</code> method.</p>
  
  <pre><code>def write(){
      def repo = Spy(PlanConditionRepositoryImpl){
          createSP(_, _) &gt;&gt; Spy(StoredProcedure){
              call() &gt;&gt; {
                  //do nothing
              }
          }
      }
      when:
      repo.write()
  
      then:
      3 * repo.createSP(_, _)
  }
  </code></pre>
  
  <p>This is how I solved it using a hack. But is there a solution using Spock's interaction-based testing without introducing an extra variable?</p>
  
  <pre><code>def "spec"() {
      given:
      def count = 0
      def spy = Spy(PlanConditionRepositoryImpl){
          createSP(_, _) &gt;&gt; {count++}
      }
  
      when:
      spy.write()
  
      then:
      count == 3
  }
  </code></pre>