Use Groovy Category implicitly in all instance methods of class

帅比萌擦擦* 提交于 2019-11-30 08:43:19

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)'
}

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:

# File: src/main/resources/META-INF/services/org.codehaus.groovy.runtime.ExtensionModule
moduleName = module
moduleVersion = 1.0
extensionClasses = SampleExtension

The extension class is pretty much defined like a normal category:

class SampleExtension {
    static String withBraces(String self) {
        "($self)"
    }
}

Can be used like:

def "Sample extension"() {
    expect: 'this'.withBraces() == '(this)'
}

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!