0

I have some class with constant to test:

public class SomeClass {
     private static final String SOME_CONST = "blabla";

And I have to use it in test, so I make (with Spring ReflectionUtils and java.lang native arsenal) smth like:

findField(SomeClass.class, "SOME_CONST").setAccessible(true);

or

makeAccessible(findField(SomeClass.class, "SOME_CONST"));

Running test

@Test
public void someTest() throws Exception {
    String s = SomeClass.SOME_CONST; 

I see my Intellij Idea stops running with error related with trying to access private field. Suppose I should use some kind of @SuppressWarnings or how to solve such an issue better?

Dmitry Adonin
  • 1,064
  • 3
  • 16
  • 36

2 Answers2

1

Testing private methods/fields is usually sign of bad design. If you don't mind to show it around, set it public or put a getter to retrieve that variable, since it's final you should not have any trouble unless it has sensitive data or it's a mutable class (not the case of a String). Or using your approach, do

Field field = TargetClass.getDeclaredField(fieldName);
field.setAccessible(true);
String someConst = (String) field.get(new SomeClass());

following this hint

Community
  • 1
  • 1
alex
  • 115
  • 6
  • Totally agree with you - I would mark constant field as public too. Unfortunately I work with legacy code and it would be better don't touch sources. – Dmitry Adonin Feb 05 '16 at 10:03
  • It's up to you to evaluate if it's too risky, in the worst case you can use the reflection approach – alex Feb 05 '16 at 10:07
  • Actually I use reflection approach :) I just don't want to use extra code for setting some fields of test class to values from tested class, I'm trying to do it gracefully. – Dmitry Adonin Feb 05 '16 at 10:11
0

As were mentioned above we can (or even should) change private fields of tested class to public, but in case you are not able to do so you can use my soulution (I tried to avoid extra fields in test class, but nobody suggested solution to my question):

private String EXTRA_FIELD_TO_HOLD_CONSTANT_VALUE_FROM_TESTED_CLASS;

@Before
public void setUp() throws Exception { 
    EXTRA_FIELD_TO_HOLD_CONSTANT_VALUE_FROM_TESTED_CLASS = 
        getPrivateStringConstantValue("SOME_CONST");
}

private String getPrivateStringConstantValue(String fieldName) throws IllegalAccessException {
    Field field = findField(CtcFraudIPAddressListServiceImpl.class, fieldName);
    field.setAccessible(true);
    return field.get(testedService).toString();
}
Dmitry Adonin
  • 1,064
  • 3
  • 16
  • 36