Toolbox is a set of small utilities to make Spock Framework Specifications more readable and easier to write
Get artifact from Maven Central Repo
Built and tested with:
- Java 17
- Groovy 4
- Spock 2
There are several "tools" which are accessible through the one entry point
com.ainrif.gears.spock_toolbox.SpockToolbox
Replicator creates objects based on given settings and check that there are no extra atoms
setters which weren't used
def pogo = SpockToolbox.replicate(CustomPogoClass) {
pogoStringField = 'value'
pogoIntField = 42
}
assert pogo.pogoStringField == 'value'
assert pogo.pogoIntField == 42
// throws exception about there are fields (maybe after new feature or refactoring)
// which were not set throug the initialization
def pogo = SpockToolbox.replicate(CustomPogoClass) {
pogoStringField = 'value'
}
Tricorder analyzes given objects
To compare two objects toolbox provides reflects
method. You can use it in assertion stanza.
// Spock Specification on Groovy
then:
SpockToolbox.reflects(actual, expected)
// Java assertion
assert SpockToolbox.reflects(actual, expected).asBoolean()
Sometimes objects have dynamic fields (like time, date, id) and should be excluded from comparison.
SpockToolbox.reflects(actual, expected)
.excludeField('fieldToxclude')
.excludeField('nestedObject.fieldToExclude')
There is special syntax to exclude map keys and array items by index
SpockToolbox.reflects(actual, expected)
.excludeField('mapField.keyToExclude')
.excludeField('arrayField.1')
.excludeField('arrayField.2')
.excludeField('arrayField') // to exclude the whole array
If some fields are undefined are dynamic they can be replaced with wildcard *
SpockToolbox.reflects(actual, expected)
.excludeField('a.*.c') // a.b.c, a.d.c etc. will be excluded
.excludeField('a.b.*') // the same as to exclude a.b
Some rules of comparison can be override with custom comparators.
Custom comparators must implement org.unitils.reflectionassert.comparator.Comparator
and set into the reflection builder:
SpockToolbox.reflects(actual, expected)
.comparator(new CustomComparator(settings))
Toolbox already has some predefined comparators which are singletons and can be used via mode
method.
Modes usually are immutable and must have default constructor.
Every customization produces new Comparator
which can be used to override the previous mode.
Modes can be found at package: com.ainrif.gears.spock_toolbox.comparator
DOUBLE_SCALE
- relaxed comparison for doubles with given scale (default is1e-14
)IGNORE_DEFAULTS
- relaxed comparison for null and default values of primitive typesIGNORE_TIME_DIFF
- objects with diff only in time are equal, also supports jsr310STRICT_ORDER
- validated orders for ordered collectionsIGNORE_ABSENT_EXPECTED_FIELDS
- if expected is superclass of actual absent fields won't generate difference
SpockToolbox.reflects(actual, expected)
.mode(STRICT_ORDER)
.comparator(DOUBLE_SCALE.scale(1e-2d))