在 grails 中进行元编程的正确方法,使其可用于单元测试

发布于 2024-12-27 07:51:36 字数 659 浏览 2 评论 0原文

我可以用以下几行向 Groovy 中的 java Integer 类型添加一个方法:

ExpandoMetaClass.EnableGlobally()
Integer.metaClass.gimmeAP = {->return 'p'}

我不知道为什么需要它,但它明白了要点。现在我可以调用 Integers 并返回“p”。现在假设我想在 grails 应用程序中使用它,这样我就可以在域对象中进行调用。我遇到的具体问题是,当我将这些元编程行放入引导程序时,所有元编程在单元测试中都不可用,因此我的单元测试失败,并出现“No method gimmeAP for java.lang.Integer”之类的错误或类似的东西。

如何更好地包含元编程,或执行引导程序的该部分,以便我可以在单元测试中使用我精心设计的语法?

我看到过这个问题: Grails - 让方法全局可用和元类编程< /a> 看来我的行 ExpandoMetaClass.EnableGlobally() 可以解决他的问题,但我使用它正确吗?

I can add a method to the java Integer type in Groovy with the lines:

ExpandoMetaClass.EnableGlobally()
Integer.metaClass.gimmeAP = {->return 'p'}

I don't know why I'd need that, but it gets the point across. Now I can make calls to Integers and get back a 'p'. Now lets say I want this in a grails app so I can make calls in the domain objects. The specific problem I'm having is that when I put those metaprogramming lines in the bootstrap all the metaprogramming isn't available in the unit tests, so my unit tests are failing with errors like "No method gimmeAP for java.lang.Integer" or something like that.

How do I either include the metaprogramming better, or execute that part of the bootstrap so I can use my tricked out syntax in unit tests?

I have seen this question: Grails - Making Methods Globally Available and Metaclass Programming and it seems my line ExpandoMetaClass.EnableGlobally() may fix his problem, but am I using it right?

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

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

发布评论

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

评论(1

如果没有 2025-01-03 07:51:36

Bootstrap 不会针对单元测试执行。我个人更喜欢创建一个执行上述元编程的mockFoo方法,然后我将从测试设置中调用mockFoo。
另请查看 GrailsUnitTestCase.registerMetaClass。在添加模拟方法之前注册元类,这样它们就不会在其他测试中泄漏。

    registerMetaClass(SecurityUtils)
    SecurityUtils.metaClass.'static'.getSubject = { ->
        return [logout: { return true } ] as Subject
    }

我知道您想让您的动态方法可用于所有单元测试,但是没有诸如用于单元测试的引导程序之类的东西。所以你必须在每次测试中都这样做。

您可以使用静态方法创建 MockHelper,并从测试设置中调用它。

Bootstrap isn't executed for unit tests. I would personally prefer to create a mockFoo method that does the above meta programming, and Then I will call the mockFoo from the test setup.
Also look at the GrailsUnitTestCase.registerMetaClass. Register metaclass before you add mock methods, so that they don't leak in other tests.

    registerMetaClass(SecurityUtils)
    SecurityUtils.metaClass.'static'.getSubject = { ->
        return [logout: { return true } ] as Subject
    }

I know you want to make your dynamic methods available to all unit tests, but there's nothing such as bootstrap for unit tests. So you have to do it in each test.

You can create a MockHelper with a static method, and call it from test setUp.

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