在GORM中创建树状结构

时间:2011-03-23 16:33:07

标签: grails groovy tree gorm

我正在尝试在GORM中正确定义树结构并遇到问题。

我有一个域对象:

class Navigation {
    Navigation parent
    List children;
    String name;

    static belongsTo = [parent: Navigation]
    static hasMany = [children: Navigation]

    static constraints = {
        parent(nullable: true);
    }
}

和测试:

void testTree() {
    Navigation root = new Navigation(name:"root");
    Navigation top1 = new Navigation(name:"home");
    Navigation top2 = new Navigation(name:"services");

    root.addToChildren(top1).addToChildren(top2).save(flush: true);

    Navigation s1 = new Navigation(name:"plumbing")
    Navigation s2 = new Navigation(name:"baking")

    top2.addToChildren(s1).addToChildren(s2).save(flush: true);

    Navigation t = Navigation.findByName("root")
    assert t.children.size() == 2
}

如果我运行此测试,我会收到此错误:

org.codehaus.groovy.runtime.InvokerInvocationException: groovy.lang.MissingMethodException: No signature of method: grails.Navigation.addToChildren() is applicable for argument types: (grails.Navigation) values: [grails.Navigation : null]

如果我将该测试的内容放入boostrap,我得到该错误,应用程序启动,除了导航表为空

我该怎么做才能解决这个问题?

1 个答案:

答案 0 :(得分:2)

您需要模拟导航域,以便在单元测试中使用GORM方法。

将其添加到测试用例的顶部:

mockDomain(Navigation)