Skip to content
Advertisement

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?

Advertisement

Answer

You must instantiate the object before you can set its field! (And you have misspelled the BufferedReader reference.)

Field reader = MyClass.class.getDeclaredField("reader");
reader.setAccessible(true);
MyClass mc = new MyClass();
StringReader stringReader = new StringReader("some string");
BufferedReader readerToSet = new BufferedReader(stringReader);
reader.set(mc, readerToSet);
mc.methodToTest();
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement