java - Is there a groovier alternative to object construction via "with"-function -


We only use Groovy for our tests, this means that all our domain classes and so forth There are general Java classes. We currently use the following techniques to create test data:

Example Java class example

  public domain domains {private string name; Private Ent ID; Private domain parent; Public string getName () {return name; } Public Zero Setname (string name) {this.name = name; } Public int getId () {return ID; } Public Zero setId (int id) {this.id = id; } GetParent (public) {back parents; } Public Zero Setpants (domain parent) {this.parent = parent; } {/ Code>  

Example object creation in Groovy

  domain testing = new domain (). {Name> "test object" id = 42 delegate} {name = "test object" id = 42 parent = new domain} / {code>  

nested creation

 < Code> domain trial = new domain (). As you can see, the  domain  object has been created and then with  as {name = "parent" id = 47 representative} representative}  

Configured Gruvi's function is the ugly thing that finally the representative returns the actual object again if we do not use it here, then instead of configured object, the result 42 .

Whether there is a Grooveer method of doing this with standard Groove functions, so there are no categories,

edit: Both answers work:

  Import spock.lang.Specification class StackOverflow Specification {DEF "Answer to Ian Roberts" (when: domain testing = new domain (name: "test object", id: 42, original: new domain (name: "parent" , Id: 47)) then: test.name == "test object" test.id == 42 test.parent.name == "parent" test.parent.id == 47} def "reply time_entence" () {When: domain test = [name: "test object", id: 42, parent: [name: "parent", id: 47]] then: test.name == "test oz ect" test.id == 42 Test.parent.name == "Parent" test.parent.id == 47}}  

You can use the" named parameter "map constructor syntax with any Java class, provided it does not have any logic builder:

  domain testing = new domain (Name: "Test Object", ID: 42, Parent: New Domain (name: "Pere Behind the scenes, Groovy no-arg creator returns after Java Bean Property Setters, and then returns the resultant object. 


Comments