ketchupex
ketchupex

Reputation: 21

Spock mock method implementation not working when checking invocations number

I have a problem with mocking methods using Spock. Below is the code which I am using. Without any change everything is working - mock implementation work properly and returns "mock" string. However if I uncomment line with invocation check (3 * notifier.test()) my mock implementation for method notify is not invoking and tests fails because notifier mock returns null. Why it works like that?

class Aaaaa extends Specification {
    class Notifier {
        def test() {
            println("Called in impl...")
            return "impl"
        }
    }

    def "Should verify notify was called"() {
        given:
        Notifier notifier = Mock(Notifier)
        notifier.test() >> {
            println("Called in mock...")
            return "mock"
        }

        when:
        notifier.test()
        notifier.test()
        def result = notifier.test()

        then:
//        3 * notifier.test()
        result == "mock"
    }
}

Upvotes: 0

Views: 1158

Answers (2)

tim_yates
tim_yates

Reputation: 171084

To post an actual answer for those who follow:

    def "Should verify notify was called"() {
        given:
        Notifier notifier = Mock(Notifier)

        when:
        notifier.test()
        notifier.test()
        def result = notifier.test()

        then:
        3 * notifier.test() >> {
            println("Called in mock...")
            return "mock"
        }
        result == "mock"
    }

Upvotes: 2

ketchupex
ketchupex

Reputation: 21

Mockito-style splitting of stubbing and mocking into two separate statements will not work

From docs: http://spockframework.org/spock/docs/1.0/interaction_based_testing.html#_combining_mocking_and_stubbing

It is required to define number of invocation in the same line where mock method is defined

Upvotes: 2

Related Questions