Using spock data table for filling objects

ε祈祈猫儿з 提交于 2019-12-03 17:27:35

In every project I have, I create what I call 'UnitTestUtils' and this class mostly contains helper methods that create domain objects with default values and allow for overrides of those values. For example:

    Person createTestPerson(Map overrides = [:]){
        Person p = new Person(name: "Jim Bob", age: 45)
        overrides.each { String key, value ->
            if(p.hasProperty(key)){
                p.setProperty(key, value)
            } else {
                println "Error: Trying to add property that doesn't exist"
            }
        }
        return p
    }

Then you can make use of this method in your class by creating a map in the same way you've already done.

    void "my test"(){
        given:
            Person person
        when:
            person = UnitTestUtils.createTestPerson(givenA)
        then:
            person.name == expected.name
            person.age == expected.age
        where:
          id| givenA        | expected
          1 | [name: "Joe"] | [name: "Joe", age: 45]
          2 | [age: 5]      | [name: "Jim Bob", age: 5]
    }

It's not a built in Spock feature, but it should provide nicely for the use case you have specified.

Basically there's no such mechanism You're looking for. If You need to provide default values for some objects/fields You need to do it Yourself and there's nothing strange, bad or unusual about it. Remember that the quality of test code is as important as the production code and it's not a bad practice to create some helper code that is used for tests only (of course this code exists only in tests hierarchy).

In this particular case instead of creating A class You can use Map.withDefault construct, but IMO using a dedicated class is much better.

Not sure what exactly you are looking for, but instead of [name: "Thomas", age: 45], you can write new A(name: Thomas, age: 45). If you want to reuse fixtures, you can do:

where:
[id, givenA] << staticUtilityMethodThatReturnsCollectionOfTwoElementCollections()

You can also create a small API (or use Groovy's built-in collection operations) to modify the defaults.

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