在grails中修改元程序的正确方法,以便在单元测试中可用 [英] Correct way to metaprogram in grails so its available in unit tests

查看:80
本文介绍了在grails中修改元程序的正确方法,以便在单元测试中可用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可以在Groovy中的java Integer类型中添加一行方法:

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

我没有知道为什么我会需要这个,但它得到了重点。现在我可以拨打Integers并返回'p'。现在让我们说我想在Grails应用程序中这样做,以便我可以在域对象中进行调用。我遇到的具体问题是,当我将这些元编程行放入引导程序中时,所有元编程在单元测试中都不可用,因此我的单元测试失败,出现错误,如No method gimmeAP for java.lang.Integer或者类似的东西。



我如何更好地包含元编程,或者执行引导的那部分,以便在单元测试中使用我的欺骗语法?



我已经看到这个问题: Grails - 使方法全局可用和Metaclass编程,看来我的行 ExpandoMetaClass.EnableGlobally()可能会解决他的问题,但我是否正确使用它?

解决方案

Bootstrap不会在单元测试中执行。我个人更喜欢创建一个执行上述元编程的mockFoo方法,然后我会从测试设置中调用mockFoo。
也看看GrailsUnitTestCase.registerMetaClass。注册metaclass,然后添加mock方法,以便它们不会在其他测试中泄漏。

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

I知道你想让你的动态方法对所有的单元测试都可用,但是没有什么比如单元测试的引导程序。所以你必须在每次测试中都这么做。



你可以用静态方法创建一个MockHelper,并从测试setUp中调用它。


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?

解决方案

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.

这篇关于在grails中修改元程序的正确方法,以便在单元测试中可用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆