OGB ObjectGraphBuilder is a builder for an arbitrary graph of beans that follow the JavaBean convention, its useful for creating test data for example.
...
| Code Block |
|---|
package com.acme
class Company {
String name
Address address
List employees = []
}
class Address {
String line1
String line2
int zip
String state
}
class Employee {
String name
int employeeId
Address address
Company company
}
|
With OGB ObjectGraphBuilder building a Company with three employees is an as easy as
| Code Block |
|---|
def builder = new ObjectGraphBuilder()
builder.classNameResolver = "com.acme"
def acme = builder.company( name: 'ACME' ){
3.times {
employee( id: it, name: 'Drone ${it}' )
}
}
assertNotNull acme
assert acme.employees.size() == 3
|
...
All 4 strategies have a default implementation that work as expected if the code follows the usual conventions for writing JavaBeans. But if by any chance any of your beans do does not follow the convention you may plug your own implementation of each strategy. Each startegy strategy setter is Closure friendly, for example
| Code Block |
|---|
builder.newInstanceResolver = { klass, attributes ->
if( attributes.foo ){
return klass.newInstance( [attributes.foo] as Object[] )
}
// default no-args constructor
klass.newInstance()
}
|
OGB ObjectGraphBuilder supports ids per node as SwingBuilder does, meaning that you can 'store' a reference to a node in the builder, this is useful to relate one instance with many others as well. Because a property named 'id' may be of business meaning in some domain models OGB ObjectGraphBuilder has a strategy named IdentifierResolver that you may configure to change the default name value ('id'). The same may happen with the property used for referencing a previously saved instance, a strategy named ReferenceResolver will yield the appropriate value (default is 'refId'):
...
For those rare occasions where OGB ObjectGraphBuilder can't locate your classes (it happens when you run a script using groovyConsole) you may define a classLoader for OGB ObjectGraphBuilder to resolve classes. Try for example running the following script inside groovyConsole and then comment out the classLoader property.
...