开发者

groovy regex test failing

In my Grails 1.3.6 app I've written this class

import org.apache.commons.lang.StringUtils

/**
 * Implementation that converts a name such as <tt>FOO_BAR</tt> to <tt>fooBar</tt>
 */
@Singleton
class CamelCaseEnumTransformer implements EnumTransformer {

    String transformName(Enum e) {

        String transformedName = e.name().toLowerCase()

        transformedName.replaceAll(/_([a-z])/) {
            it[1].toUpperCase()
        }
        StringUtils.remove(transformedName, '_')
    }
}

I've created this test case:

class EnumTransformerTests extends GroovyTestCase {

    private static enum TestEnum {
        A, FOO, FOO_BAR, FOO_BAR_123,
    }

    void testCamelCaseTransformer() {
        EnumTransformer transformer = CamelCaseEnumTransformer.instance
        assertEquals 'a', transformer.transformName(TestEnum.A)
        assertEquals 'foo', transformer.transformName(TestEnum.FOO)

        // This test fails on the line below
        assertEquals 'fooBar', transformer.transformName(TestEnum.FOO_BAR)
    }
}

The test fails on the line marked above. I reckon the problem must be related to the replaceAll method, because this is the first time that the closure passed as the second argument to this method is executed.

The error I get is:

groovy.lang.MissingMethodException: No signature of method: 
CamelCaseEnumTransformer$_transformName_closure1.doCall() 
is applicable for argument types: (java.lang.String, java.lang.String) values: [_b, b]

What's particularly strange, is that if I run the equivalent code below in the Groovy console, everything seems to work fine.

@Singleton
class CamelCaseEnumTransformer {

    String transformName(Enum e) {

        String transformedName = e.name().toLowerCase()

        transformedName.replaceAll(/_([a-z])/) {
            it[1].toUpperCase()开发者_StackOverflow
        }
    }
}

enum TestEnum {
    A, FOO, FOO_BAR, FOO_BAR_123,
}

def transformer = CamelCaseEnumTransformer.instance
assert 'fooBar' == transformer.transformName(TestEnum.FOO_BAR)


From the error message text, it looks like the closure should accept 2 arguments for the 2 matches in your regex. Try the following:

    transformedName.replaceAll(/_([a-z])/) { wholeMatch, capturedGroups ->
        capturedGroups[0].toUpperCase();
    }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜