所以我有一个java类,有3个私有(private)字段
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 测试来测试这些私有(private)字段
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();
}
}
}
尝试访问私有(private) guid 字段时出现错误。即使在创建零参数构造函数之后我也尝试过这个。我应该如何访问这里的私有(private)成员?
编辑 我想通了,如果其他人需要的话,我已经更新了我的回复。
附: 我怎样才能关闭这个问题>
最佳答案
最好测试外部可见的行为(行为,而不是 getter 和 setter)。如果您的代码没有改变行为,您应该将其删除。
(此外,您可能希望在将列表存储在字段中(以及在检查有效性之前)之前复制列表。)
关于java - 私有(private)成员(member)无法访问?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9440620/