在类的所有实例方法中隐式使用 Groovy Category [英] Use Groovy Category implicitly in all instance methods of class
问题描述
我有一个简单的 Groovy 类别类,它向 String 实例添加方法:
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)'
}
}
}
然而,我想要实现的是能够指定在 MyTest
的每个实例方法的范围内使用类别 SampleCategory
所以我不t 必须在每个方法中指定 use(SampleCategory) { ... }
.
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.
有可能吗?
推荐答案
您可以使用 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:
@Before void setUp() {
String.mixin(SampleCategory)
}
@After void tearDown() {
String.metaClass = null
}
@Test
void shouldDoThat() {
assert 'that'.withBraces() == '(that)'
}
这篇关于在类的所有实例方法中隐式使用 Groovy Category的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!