Spock Mock not working for unit test

余生颓废 提交于 2019-12-07 15:54:26
Jon Peterson

From our discussion on a different one of @smeeb's questions, I looked into this a bit more since I was very confused why this wasn't working.

I created my own test.

class SomeTest extends Specification {

    static class Driver {

        String getName(Superclass superclass) {
            return superclass.name
        }
    }

    static abstract class Superclass {
        String name
    }

    static class Subclass extends Superclass {
    }


    def 'test'() {
        given:
        def driver = new Driver()
        def subclass = Mock(Subclass)

        subclass.name >> 'test'

        expect:
        driver.getName(subclass) == 'test'
    }
}

It failed with the same problem that @smeeb saw.

driver.getName(subclass) == 'test'
|      |       |         |
|      null    |         false
|              Mock for type 'Subclass' named 'subclass'

I tried changing a few different things and found that when I either removed the abstract modifier from Superclass or changed the return superclass.name to return superclass.getName() the test began working.

It seems there is a weird interaction on the Groovy-level between getting inherited public fields from an abstract superclass using the auto-generated accessors.

So, in your case either remove abstract modifier from FooBaz, or change your code to:

@Override
String toString() {
    "${fizz1.getName()} - ${fizz2.getName()}"
}

If you change your specification to this:

class CarSpec extends Specification {
    def "toString() generates a correct string"() {
        given: "a Car with some mocked dependencies"
        String f1 = 'fizzy'
        String f2 = 'buzzy'
        Fizz fizz1 = Mock()
        Fizz fizz2 = Mock()

        Car car = new Car(1L, fizz1, fizz2)

        when: "we call toString()"
        String str = car.toString()

        then: "we get a correctly formatted string + getProperty('name') is called once on each Mock"
        "$f1 - $f2" == str

        1 * fizz1.getProperty('name') >> f1
        1 * fizz2.getProperty('name') >> f2
    }
}

So you define the interactions in the then block, then it should all work fine...

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!