I have the following in the test setup:
def originalPostAsXml = RestClient.&postAsXml
RestClient.metaClass.'static'.postAsXml = {
String uriPath, String xml ->
return 65536
}
and in the test cleanup:
RestClient.metaClass.'static'.postAsXml = originalPostAsXml
But when the next test runs, when it tries to execute RestClient.postAsXml, it runs into a StackOverflowError:
at groovy.lang.Closure.call(Closure.java:282)
It looks like RestClient.postAsXml recursively points to itself. What's the right way to reset a mocked-out static method?
In a unit test, I often set the metaclass to null
in the tearDown()
which seems to allow the class to work as it did originally without my modifications.
example:
void setUp() {
super.setUp()
ServerInstanceSettings.metaClass.'static'.list = {
def settings = [someSetting:'myOverride'] as ServerInstanceSettings
return [settings]
}
}
void tearDown() {
super.tearDown()
ServerInstanceSettings.metaClass.'static'.list = null
}
If you are using JUnit4 you can use @AfterClass
instead in this case which makes more sense perhaps.
I find that simply setting <Class>.metaClass = null
works for me.
Spock Example:
def "mockStatic Test"(){
given:
RestClient.metaClass.static.postAsXml = {
String uriPath, String xml ->
return 65536
}
when:
//some call that depends on RestClient.postAsXml
then:
//Expected outcomes
cleanup:
//reset metaclass
RestClient.metaClass = null
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With