I am trying to initialize a private field from a class in order to unit test its methods. For that I am using reflection but I am always getting an IllegalArgumentException and I don't understand what I am doing wrong.
My code looks something like this:
public class MyClass {
private BufferedReader reader;
public void methodToTest(){
doSomethingwith(reader);
}
}
public class testClass {
@Test
public void testMethod() {
Field reader = MyClass.class.getDeclaredField("reader");
reader.setAccessible(true);
StringReader stringReader = new StringReader("some string");
BufferedReader readerToSet = new BufferedReader(stringReader);
reader.set(readerToSet, readerToSet);
MyClass instance = new MyClass();
instance.methodToTest();
}
}
I get this error when I am trying to run the test:
Can not set java.io.BufferedReader field MyClass.receiveReader to java.io.BufferedReader
I also tried getting the value of the field from the class and setting to the reader. But the value returns null and I still get the same error message.
Any idea how I could initialize the field so I can test the method?
Yeah you can use reflections to access private variables.
Use the TestVisible annotation to allow test methods to access private or protected members of another class outside the test class. These members include methods, member variables, and inner classes. This annotation enables a more permissive access level for running tests only.
If we want to access Private Field and method using Reflection we just need to call setAccessible(true) on the field or method object which you want to access. Class. getDeclaredField(String fieldName) or Class. getDeclaredFields() can be used to get private fields.
You can also use spring-test if you are using spring.
import org.springframework.test.util.ReflectionTestUtils;
ReflectionTestUtils.setField(notificationService, "timeToLive", 90L);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With