Search code examples
groovyspock

How to correctly verify mock method invocation in Spock framework?


I'm trying to test a method using the Spock framework, but I'm running into an issue when verifying the mock method invocation. Here's my code:

package com.workato.agent.smb

import spock.lang.Specification

import java.util.function.Supplier

class SomeSpec extends Specification {

    def "test"() {
        given:
        def resource = "ABC"
        def supp = Mock(Supplier)
        supp.get() >> { args ->
            resource
        }

        when:
        def res = supp.get()

        then:
        res == resource
        // 1 * supp.get()
    }
}

When I uncomment the last line in the "then" block (1 * supp.get()), the test fails with the following error:

Condition not satisfied:

res == resource
|   |  |
null|  ABC
false

In debug mode, the breakpoint inside the closure {args -> resource} doesn't trigger when this line is uncommented.

How can I correctly verify that the get() method on the mock Supplier is called once without causing the test to fail?


Solution

  • I think it should be

      def "test"() {
        given:
        def resource = "ABC"
        def supp = Mock(Supplier)
    
        when:
        def res = supp.get()
    
        then:
        res == resource
        1 * supp.get() >> resource
      }
    

    Or, somewhat more compactly:

      def "test"() {
        given:
        def resource = "ABC"
        def supp = Mock(Supplier) {
          1 * get() >> resource
        }
    
        expect:
        supp.get() == resource
      }