是否有通过“with”-function进行对象构造的更长的替代方案

时间:2014-02-18 17:08:46

标签: java groovy

我们仅将Groovy用于测试,这意味着我们所有的域类等仍然是普通的Java类。为了轻松创建测试数据,我们目前使用以下技术:

示例Java类


public class Domain {
    private String name;
    private int id;
    private Domain parent;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public Domain getParent() {
        return parent;
    }

    public void setParent(Domain parent) {
        this.parent = parent;
    }
}

Groovy中的对象构造


Domain test = new Domain().with {
    name = "Test Object"
    id = 42

    delegate
}

嵌套构造


Domain test = new Domain().with {
    name = "Test Object"
    id = 42
    parent = new Domain().with {
        name = "Parent"
        id = 47

        delegate
    }

    delegate
}

如您所见,创建了Domain对象,然后通过Groovy的with函数进行配置。这里丑陋的事情是最后的delegate,它再次返回实际的对象。如果我们不在这里使用它,结果将是42而不是配置的对象。

使用标准的Groovy函数是否有Groovier方法来执行此操作,因此没有类别,mixins或自定义帮助函数。


编辑: 添加了嵌套对象构造示例。

编辑2: 两个答案的工作都有效:


import spock.lang.Specification


class StackOverflow extends Specification {

    def "Answer Ian Roberts" () {
        when:
        Domain test = new Domain(
                name: "Test object",
                id: 42,
                parent: new Domain(name: "Parent", id: 47))

        then:
        test.name == "Test object"
        test.id == 42
        test.parent.name == "Parent"
        test.parent.id == 47
    }

    def "Answer tim_yates"() {
        when:
        Domain test = [
            name: "Test object",
            id: 42,
            parent: [name:"Parent", id:47]
        ]

        then:
        test.name == "Test object"
        test.id == 42
        test.parent.name == "Parent"
        test.parent.id == 47
    }
}

2 个答案:

答案 0 :(得分:5)

您可以将“命名参数”映射构造函数语法与任何Java类一起使用,前提是它具有无参数构造函数:

Domain test = new Domain(
    name:"Test object",
    id:42,
    parent:new Domain(name:"Parent", id:47))

在幕后,Groovy将调用no-arg构造函数,后跟Java Bean属性setter,然后返回结果对象。

答案 1 :(得分:3)

不确定它是否适用于POJO,但您可以尝试:

Domain test = [ name:'Test Object', id: 42 ]
相关问题