I am writing tests for a project and I want to access to private field of a class that otherwise should not be accessed. The reason behind this is that I don’t want to fill the database with meaningless test datas so I am creating the test data within the code. Since there shouldn’t be any manual insertions to the list using the code I need to use reflection to achieve it. I am using @Autowired annotation to create an instance of the class. I am also trying to use reflection to get the private field of this said instance. Usually I expect it to get the required field but it always returns null. When I debugged the test I saw that all fields of the injected object appear as null.
I assumed that the field’s returned value wasn’t being properly casted even though it was not throwing a ClassCastException. I tried getting the field as Map<?, ?> and Object but all was in vain as it returned null. Here is the latest version of the code:
@Autowired
private MyClass myClass;
@Test
void shouldGetAllScenarioConfigurations() throws NoSuchFieldException, IllegalAccessException {
Field myField = MyClass.class.getDeclaredField("fieldToBeAccessed");
myField.setAccessible(true);
Map<?, ?> desiredMap = (Map<?, ?>) myField.get(myClass);
desiredMap.clear();
//do something
myField.setAccessible(false);
}
This tests throws an exception at desiredMap.clear()
part as desiredMap returns null. MyClass class is declared as a component with @Component annotation and it implements SmartLifecycle interface. Is using reflection with @Autowired causing this issue? If so is there a way to make them work together?
8