当前位置: 动力学知识库 > 问答 > 编程问答 >

java - 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?

网友答案:

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();
网友答案:

Answer by @kocko is correct for most cases. But if you do not want to show implementation details, you can just do not set access level modifier to your field (default access level).

So in your case field declaration should look like this:

public class MyClass {
    BufferedReader reader;
    ...
}

And then make sure your test is located in same package with your code, but in test directory. If all is done right, you will be able to access it with out any hacks.

Note: default access level means that the thing is visible only inside class and package.

分享给朋友:
您可能感兴趣的文章:
随机阅读: