Question

Given following interface:

interface Bundle {
    String getName()

    String getVersion()
}

and following method:

String log(Bundle b) {
    return "${b.getName()}: ${b.getVersion()}"
}

this spock test is failing:

def "my test"() {
        given:
        def bundle = Mock(Bundle)
        bundle.getName() >> "name"
        bundle.getVersion() >> "1.0.0"

        when:
        def x = log(bundle)

        then:
        x == "name: 1.0.0"
        1 * bundle.getName()
        1 * bundle.getVersion()

    }

here is the error:

condition not satisfied:
x == "name: 1.0.0"
| |
| false
| 8 differences (27% similarity)
| n(ull): (null-)
| n(ame): (1.0.0)
null: null

If i remove two verifications (1 * bundle.getName() and 1 * bundle.getVersion()) the test will be green.

Any idea what's wrong with my code?

Was it helpful?

Solution

Mocking and stubbing of the same invocation need to happen together (either in the given or then block):

...
then:
1 * bundle.getName() >> "name"
1 * bundle.getVersion() >> "1.0.0"
x == "name: 1.0.0"

Combining Mocking and Stubbing in the Spock Reference Documentation explains this in more detail.

An alternative is to get rid of the mocking part (1 * bundle.getName() etc.), which may not be all that necessary/helpful here.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top