I am trying to write some Spock tests using Groovy to test Java code (in particular, servlet filter). I have private static
and private static final
variables that I would like to make fun of, but I cannot determine if there is a way to do this. I know that metaClass
is available for methods, is there something similar for variables?
For example, I have:
public class MyFilter implements Filter { private static WebResource RESOURCE; private static final String CACHE_KEY = "key-to-be-used-for-cache"; ... actual methods, etc ... }
I tried using Mock(MyFilter)
as well as using Java reflection to change the value (based on this question and answer Changing a private static final field using Java reflection ).
I would like to do this without adding something like Mockito or other frameworks, if possible, just use simple Groovy and Spock.
Thanks for any ideas!
UPDATE 1
At least for private static
variables, I got the following:
Field field = MyFilter.class.getDeclaredField("CACHE_KEY") field.setAccessible(true) field.set(null, "new-key-value")
But I still could not get around the final
aspect.
UPDATE 2
Thanks Xv. Now I can install this with the following:
Field field = MyFilter.class.getDeclaredField("CACHE_KEY") field.setAccessible(true) Field modifiersField = Field.class.getDeclaredField("modifiers") modifiersField.setAccessible(true); modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL); field.set(null, "new-key-value")
source share