title: Spock spy registers too few invocations (none) of Groovy method
body: <p>I have written a Groovy extension library that adds extra methods to the List class. I am trying to write tests for this using Spock but I am unable to get some of my tests to work.</p>
  
  <p><strong>The code</strong></p>
  
  <p>There are a number of methods that all have the same form. I have added methods that work the same as <code>tail()</code> (or <code>head()</code>, <code>first()</code>, etc.) but that will just return <code>null</code> if the List is empty, rather than throwing an Exception. An example is shown below (println()s added for troubleshooting):</p>
  
  <pre><code>public static def tailIfAny(List list) {
  
      println "tailIfAny() list.size(): ${list.size()}"
  
      def r = list.size() ? list.tail() : null
      println "r: $r"
      return r
  }
  </code></pre>
  
  <p>I want to have two tests for <code>tailIfAny()</code>. The first test should check that no exception is thrown if you call the method on an empty List. This was straightforward and works. The other test I want to write is to check that <code>tail()</code> is called if the list is not empty.</p>
  
  <p><strong>The test</strong></p>
  
  <p>This is my test to check that <code>tail()</code> is called if the List is not empty:</p>
  
  <pre><code>def "tailIfAny() calls tail()"() {
  
      setup:
      def list = Spy(ArrayList)
      list &lt;&lt; 'a'
      list &lt;&lt; 'b'
  
      when:
      println "list ${list} -- ${list.size()}"
      println "Before tailIfAny()"
      list.tailIfAny()
      println "After tailIfAny()"
  
      then:
      1 * list.tail()
  }
  </code></pre>
  
  <p><strong>The error message</strong></p>
  
  <p>When I run me tests I get this failure message:</p>
  
  <pre>Too few invocations for:
  
  1 * list.tail()   (0 invocations)
  
  Unmatched invocations (ordered by similarity):
  
  1 * list.toArray()
  1 * list.iterator()
  3 * list.size()
  1 * list.isEmpty()
  
  
      at org.spockframework.mock.runtime.InteractionScope.verifyInteractions(InteractionScope.java:78)
      at org.spockframework.mock.runtime.MockController.leaveScope(MockController.java:76)
      at com.fgi.extensions.ListExtensionsTests.add element in setup(ListExtensionsTests.groovy:65)</pre>
  
  <p>But from the stdout output (below) I can see that <code>tail()</code> should have been called.</p>
  
  <p><strong>The standard out from the tests</strong></p>
  
  <pre>list [a, b] -- 2
  Before tailIfAny()
  tailIfAny() list.size(): 2
  r: [b]                      // This tells me that tail() is being called.
  After tailIfAny()</pre>
  
  <p><strong>Can anyone shed some light on why Spock thinks that <code>tail()</code> isn't being called? or is there something going on here that I'm missing?</strong></p>
  
  <p>Thanks.</p>