Using the spot data table to populate objects

I am using Spock for the first time. Since we use a complex domain model, it would be convenient to have a mechanism that allows me to create complete objects from data given by spot tables. I do not want to give all the values ​​every time, I just want to set the values ​​to the given in the datable. Therefore, default values ​​must be defined somewhere.

Yes, I know that I can write on my own, but maybe there is a ready-made solution.

Example

class A {
   String name
   int age
}

Point table

id | givenA                     | ...
1  | [name: "Michael"]          | ...
2  | [name: "Thomas", age: 45 ] | ...
  • => A.name = "Michael", A.age = defined default value somewhere
  • => A.name = "Thomas" A.age = 45 (because I am overwriting the default value)
+4
source share
4

, , , "UnitTestUtils", , . :

    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
    }

, , .

    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]
    }

Spock, .

+10

, . /, , , . , , , , (, ).

A Map.withDefault, IMO .

+1

Builder ? , A , .

A.builder()
     .withDefaults(HereAreDefaultValues.class)
     .withName('Michael')
     .build()

, . .

, , , , , . , ( ), . Builder , , .

+1

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

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

You can also create a small API (or use the Groovy collection built-in operations) to change the default values.

0
source

All Articles