1

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

kriegaex
  • 63,017
  • 15
  • 111
  • 202
XC.sun
  • 13
  • 3
  • 1
    This question is a duplicate of [that one](https://stackoverflow.com/a/66219228/1082681), [that one](https://stackoverflow.com/a/53900761/1082681), [that one](https://stackoverflow.com/a/61113581/1082681) and several others. See also Spock manual chapter ["Combining mocking and stubbing"](https://spockframework.org/spock/docs/2.1/all_in_one.html#_combining_mocking_and_stubbing). – kriegaex Apr 09 '22 at 03:26

1 Answers1

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"
    }
tim_yates
  • 167,322
  • 27
  • 342
  • 338