vendredi 5 octobre 2018

Using spocks method counter on mocks out of compositions?

I have an issue with creating test data with spock framework. To follow "composition over inheritance", I have a class to create testdata for my unit tests. As a simple snipped it looks like this:

class TestData extends Specification{

    Foo createFoo(){
        GroovyMock(Foo){
            doSomething() >> "MOCKED!"
        }
    }
}

When I write a Test, i like to test, if and how often the method has been invoked. Like this

def "simple test"(){
    given:
    TestData testData = new TestData()
    Foo foo = testData.createFoo()

    when:
    println foo.doSomething()

    then:
    1 * foo.doSomething()
}

I know, this test doesn't makes sense. It's just for illustriating the behavior.

I would expect the console output "MOCKED!" and a "green result" of that test, since doSomething() has been invoked 1 time. But that isn't the case. Actually, on console there is the output "MOCKED!". But the test result is red:

Too few invocations for:

1 * foo.doSomething()   (0 invocations)
[...]

When i mock Foo directly, everything works fine: def "simple test"(){ given: Foo foo = Mock(Foo)

    when:
    println foo.doSomething()

    then:
    1 * foo.doSomething()
}

Anyone has an idea how to treat this without deriving my testclass from TestData?

Aucun commentaire:

Enregistrer un commentaire