是否可以在测试中模拟瞬态场?
我有一个包含瞬态字段的类。但类的其他部分是可序列化的。 在测试中,我模拟字段和类,并在深度复制函数中使用模拟的类对象,如下所示:
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.NotSerializedException 。请问测试中是否无法识别瞬态场?我使用mockito作为我的框架。
I have a class that contains a transient field. But the other part of the class is serializable.
In the tests I mock the field and the class and use the mocked class object in a deep copy function which looks like below:
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 () {...}
the writeObject(original) method is supposed to write all non-transient and non-static fields. But I've got an error saying java.io.NotSerializableException for the mock transient field. I wonder if the transient field cannot be recognised in the tests? I use mockito as my framework.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
“我嘲笑这个领域和这个班级”是什么意思?
我刚刚基于这个虚拟类进行了一个快速测试:
ChildClass
只是一个空的(非Serialized
)类。测试看起来像这样:...并且不会抛出任何 NotSerializedException。
你想测试什么?深层复印机还是传递给它的类?
What do you mean by "I mock the field and the class" ?
I just whipped up a quick test based on this dummy class:
ChildClass
is just an empty (non-Serializable
) class. The test looks like this:... and that doesn't throw any NotSerializableException.
What are you trying to test? The deep-copier or the class that is passed to it?