0

I have a private static final int LIMIT = 1000 in my Spring Service.

I am trying to override the value of LIMIT in my test case using reflection and all but its not working. I am doing integration test so can't use Mockito or Mock.

    Field maxFetchAllowed Manager.getClass().getDeclaredField("LIMIT");
    maxFetchAllowed.setAccessible(true);
    int modifiers = maxFetchAllowed.getModifiers();
    Field modifierField = maxFetchAllowed.getClass().getDeclaredField("modifiers");
    modifiers = modifiers & ~Modifier.FINAL;
    modifierField.setAccessible(true);
    modifierField.setInt(maxFetchAllowed, modifiers);
    maxFetchAllowed.set(null, 100); //set the value correctly 
    System.out.println(maxFetchAllowed.get(null)); // shows 100

but when I call the create method to test, it still has 1000 in it

manager.create() // still has 1000 
plzdontkillme
  • 1,497
  • 3
  • 20
  • 38
  • Emphasis from the duplicate on: _Even then, there are a number of complications. If a final field is initialized to a compile-time constant in the field declaration, changes to the final field may not be observed, since uses of that final field are replaced at compile time with the compile-time constant._ Your `LIMIT` variable is a constant expression. Anywhere you use `LIMIT`, it'll have been replaced with its value. You'll only be able to see the new value by retrieving it through reflection. – Sotirios Delimanolis May 18 '16 at 04:52
  • Let me ask in this, how can i over write the value of LIMIT? or what is the standard practice to define such variables so that they can be tested. I don't want to create 1000 objects to test if the validation exception is thrown or not but I want to over write value to 10. – plzdontkillme May 18 '16 at 05:10
  • As I said, you can't change the value in existing code that accesses the field directly because it's a constant expression. You wouldn't typically test things like this. I believe mocking libraries like PowerMock are able to change their values through some instrumentation. Might want to look into that. – Sotirios Delimanolis May 18 '16 at 05:13

0 Answers0