Groovy and the Metaclass

2019-08-26 02:12发布

问题:

I am attempting to use the metaclass to overwrite a static method in a test.

The method is:

org.boon.HTTP.jsonRestCallWithHeaders 

It it is a Java class, and it is beyond my control.

The declaration is:

public static Response jsonRestCallWithHeaders(
            final String url,
            final Map<String, ?> headers
    )

I am attempting to overwrite the method with a closure via:

HTTP.metaClass.static.jsonRestCallWithHeaders =  { String url, Map<String, ?> headers ->
            if (url.path?.contains('/quotes')) {
                [prop1:value1,
                        prop2: value2 ] as JSON }

However, when it hits that redirect request it doesn't attempt to rewrite the method. It initializes the HTTP class, and attempts to call the HTTP.get function.

My question is: Why is this definition for the jsonRestCallWithHeaders method calling the HTTP::get static method?

A picture of the stacktrace:

I am using Groovy 2.1.9, Grails: 2.3.8. The code is being run within a test environment.

回答1:

I have tested the following and it works:

HTTP.getMetaClass().static.jsonRestCallWithHeaders =  { String url, Map<String, ?> headers ->
    // ...
}