I\'m trying to write some Spock tests with Groovy to test some Java code (specifically a servlet Filter). I have some private static
and private static fi
Based on what I learned from https://stackoverflow.com/a/25031713/239408, this works for me in spock
import java.lang.reflect.Field
import java.lang.reflect.Modifier
...
def setup() {
Field field = BackendCredentials.getDeclaredField("logger")
field.setAccessible(true);
Field modifiersField = Field.class.getDeclaredField("modifiers");
modifiersField.setAccessible(true);
modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL);
field.set(null, Mock(Logger))
}
Looks like you are missing the unsetting of the Modifier.FINAL
flag.
Either you need to use PowerMock (or another similar solution), or refactor your code. Spock does not support mocking of private/static/final methods on its own. This limitation is also present in Mockito, so that must give you a hint on best-practices.