我有一个包含瞬态字段的类。但是该类的另一部分是可序列化的。在测试中,我模拟了字段和类,并在深拷贝函数中使用了模拟的类对象,如下所示:
try {
final ByteArrayOutputStream bytesOut = new ByteArrayOutputStream();
objectOut = new ObjectOutputStream(bytesOut);
// serialize and pass the object
objectOut.writeObject(original);
objectOut.flush();
final ByteArrayInputStream bytesIn =
new ByteArrayInputStream(bytesOut.toByteArray());
objectIn = new ObjectInputStream(bytesIn);
@SuppressWarnings("unchecked")
final T clone = (T) objectIn.readObject();
// return the new object
return clone;
}
catch () {...}
writeObject(original) 方法应该写入所有非瞬态和非静态字段。但是我有一个错误,说模拟瞬态字段的 java.io.NotSerializableException 。我想知道在测试中是否无法识别瞬态场?我使用 mockito 作为我的框架。