Using Spock to Retrieve Private Static Final Variables in Java

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") 
+6
source share
2 answers

Based on what I learned from fooobar.com/questions/816165 / ... , 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)) } 

It looks like you were unable to clear the Modifier.FINAL flag.

+5
source

Either you need to use PowerMock (or another similar solution), or reorganize your code. Spock does not support mocking private / static / final methods on his own. This limitation is also present in Mockito, so you should give you a hint of best practices.

+1
source

Source: https://habr.com/ru/post/979872/


All Articles