Using Spock to mock private static final variables in Java

后端 未结 2 445
感情败类
感情败类 2020-12-16 19:21

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

相关标签:
2条回答
  • 2020-12-16 20:01

    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.

    0 讨论(0)
  • 2020-12-16 20:23

    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.

    0 讨论(0)
提交回复
热议问题