隐式地在类的所有实例方法中使用Groovy类别

隐式地在类的所有实例方法中使用Groovy类别

本文介绍了隐式地在类的所有实例方法中使用Groovy类别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  final class SampleCategory {

static string withBraces(String self){
($ self)
}

}

我想在我的单元测试中使用这个类(例如)。它看起来像这样:

  class MyTest {
@Test
void shouldDoThis(){
使用(SampleCategory){
assert'this'.withBraces()=='(this)'
}
}

@Test
void shouldDoThat(){
use(SampleCategory){
assert'that'.withBraces()=='(that)'
}
}
}

然而,我想要实现的是能够指定该类别 SampleCategory 用于 MyTest 的每个实例方法的范围中,所以我不必指定 use(SampleCategory){ ...} 在每种方法中。



可能吗?

解决方案

您可以使用mixin将类别直接应用于String的metaClass。将null分配给metaClass以将其重置为常规默认值。例如:

  @Before void setUp(){
String.mixin(SampleCategory)
}

@After void tearDown(){
String.metaClass = null
}

@Test
void shouldDoThat(){
assert'that'.withBraces()=='(that)'
}


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?

解决方案

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类别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 06:58