'How to verify if method was called when the method is mocked in Spock

I have some strange error when using spock. I mock some method, and it's worked, and the behavior is corrent. But when I want to verify if the mocked method is called, the mock will not work at all.

Here is sample code:

import spock.lang.Specification
class MockServiceSpec extends Specification {

    private TestService service = Mock()

    void setup() {
        service.get() >> {
            println "mocked method called" // print some log and it proves that this mock is realy not work in second test
            return "mocked result"
        }
    }

    def "worked perfect"() {
        when:
        String r = service.get()
        then:
        r == "mocked result"
    }
    
    def "verify if get() is called and return null"() {
        when:
        String r = service.get()
        then:
        r == null  // why??
        1 * service.get()
    }

    class TestService {
        public String get() {
            return "real result";
        }
    }
}

Both tests pass:

both tests pass



Solution 1:[1]

You are overriding the mocked method, and not providing a return value, so it results in null. Try:

    def "verify if get() is called and returns exactly what it's told to"() {
        when:
        String r = service.get()

        then:
        r == "ok"  // returns exactly what you mock on the next line

        1 * service.get() >> "ok"
    }

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 tim_yates