所以我有一个java类,有3个私有字段
public class Parcel {
private String guid;
private List<String> files;
private String zipFileName;
public Parcel (List<String> files, String zipFilePath){
UUID uuid = UUID.randomUUID();
guid = uuid.toString();
zipFileName = zipFilePath + File.separator + guid + File.separator + ".zip";
if ((files != null) && (!files.isEmpty())){
this.files = files;
}
}
}
现在,我正在编写JUnit测试来测试这些私有字段
public class ParcelTest {
@Test
public void parcelObject() {
String zipFilePath = "/path/to/folder";
List<String> files = new ArrayList<String>();
files.add("/path/to/folder/test1");
files.add("/path/to/folder/test2");
Parcel parcel = new Parcel(files, zipFilePath);
Class<? extends Parcel> parcelClass = parcel.getClass();
try {
Field guid = parcelClass.getDeclaredField("guid");
guid.setAccessible(true);
System.out.println(guid.get(parcel));
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchFieldException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
尝试访问私有 guid 字段时出错。我甚至在创建零参数构造函数后尝试过这个。我应该如何访问私人会员?
EDIT 我想出来了,如果其他人需要,我已经更新了我的回复。
P.S: 我如何关闭此问题&gt;
答案 0 :(得分:2)
测试外部可见行为(行为,而不是getter和setter)要好得多。如果您的代码没有改变行为,则应删除它。
(另外,您可能希望在将其列入字段之前(并在检查有效性之前)复制您的列表。)
答案 1 :(得分:0)
为什么你没有公开的getter或setter而不是处理反射?