Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access a private field for a junit test

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?

like image 727
schmimona Avatar asked Jan 09 '15 09:01

schmimona


People also ask

Can JUnit access private variables?

Yeah you can use reflections to access private variables.

How do you access private variables in test class?

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.

How do I access private field?

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.


1 Answers

You can also use spring-test if you are using spring.

import org.springframework.test.util.ReflectionTestUtils;

ReflectionTestUtils.setField(notificationService, "timeToLive", 90L);
like image 185
Joseph Rajeev Motha Avatar answered Nov 04 '22 05:11

Joseph Rajeev Motha