在类的所有实例方法中隐式使用 Groovy Category
我有简单的 Groovy 类别类,它将方法添加到 String 实例:
final class SampleCategory {
static String withBraces(String self) {
"($self)"
}
}
我想在我的单元测试中使用此类别(例如)。它看起来像这样:
class MyTest {
@Test
void shouldDoThis() {
use (SampleCategory) {
assert 'this'.withBraces() == '(this)'
}
}
@Test
void shouldDoThat() {
use (SampleCategory) {
assert 'that'.withBraces() == '(that)'
}
}
}
但是,我想要实现的是能够指定类别 SampleCategory
在 MyTest
的每个实例方法的范围内使用,所以我不必在每个方法中指定 use(SampleCategory) { ... }
。
是否可以?
I have simple Groovy category class which adds method to String instances:
final class SampleCategory {
static String withBraces(String self) {
"($self)"
}
}
I want to use this category in my unit tests (for example). It looks like this:
class MyTest {
@Test
void shouldDoThis() {
use (SampleCategory) {
assert 'this'.withBraces() == '(this)'
}
}
@Test
void shouldDoThat() {
use (SampleCategory) {
assert 'that'.withBraces() == '(that)'
}
}
}
What I'd like to achieve, however, is ability to specify that category SampleCategory
is used in scope of each and every instance method of MyTest
so I don't have to specify use(SampleCategory) { ... }
in every method.
Is it possible?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以使用 mixin 将类别直接应用于 String 的元类。将 null 分配给元类以将其重置为常规默认值。例如:
You can use mixin to apply the category directly to String's metaClass. Assign null to the metaClass to reset it to groovy defaults. For example:
现在您可以选择使用扩展模块而不是类别:
http://mrhaki.blogspot.se/2013/01 /groovy-goodness-adding-extra-methods.html
从好的方面来说,Intellij 会识别扩展。我刚刚注意到它甚至不需要像链接所建议的那样是一个单独的模块,只需将 META-INF/services/org.codehaus.groovy.runtime.ExtensionModule 添加到项目中:
扩展类几乎是像普通类别一样定义:
可以这样使用:
如果您使用 Spock,则可以在规范上使用 @Use 注释。这样做的缺点是 Intellij 无法识别它。
Now you have the option to use extension modules instead of categories:
http://mrhaki.blogspot.se/2013/01/groovy-goodness-adding-extra-methods.html
On the plus side Intellij will recognize the extensions. I've just noticed that it doesn't even need to be a separate module as suggested by the link, just add META-INF/services/org.codehaus.groovy.runtime.ExtensionModule to the project:
The extension class is pretty much defined like a normal category:
Can be used like:
If you are using Spock there is a @Use annotation that can be used on the specifications. The drawback with that is that Intellij will not recognize it.