在 GORM 中创建树状结构

发布于 2024-10-25 02:53:27 字数 1269 浏览 5 评论 0原文

我试图在 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,我不会收到该错误,并且应用程序启动向上,除了导航表为空

我能做什么来解决这个问题?

I am trying to correctly define a tree structure in GORM and having trouble.

i have one domain object:

class Navigation {
    Navigation parent
    List children;
    String name;

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

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

and the test:

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
}

if i run this test, i get this error:

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]

and if i place the contents of that test into boostrap, i dont get that error, and the application starts up, except the navigation table is empty

what can i do to fix this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

像极了他 2024-11-01 02:53:28

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

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

mockDomain(Navigation)

You need to mock the Navigation domain so that you can use the GORM methods in your unit test.

Add this to the top of your test case:

mockDomain(Navigation)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文