为什么要为此使用模拟框架?
往返测试将是最简单和最快的 - 所以只需序列化然后反序列化并比较两个实例。不要使用你的 equals() 方法进行比较,即使它已经过很好的测试。
您还需要测试边缘,例如,为了确保在反序列化时重新创建/重新添加瞬态字段,您可以使用readResolve()
可以在IBM DeveloperWorks上找到一些有用的提示
这是一个示例往返测试:
public class WritableTest {
public class CustomObj implements Writable {
private String value;
public CustomObj(String v) {
value = v;
}
@Override
public void write(DataOutput out) throws IOException {
out.writeUTF(value);
}
@Override
public void readFields(DataInput in) throws IOException {
value = in.readUTF();
}
}
@Test
public void roundTripSerialization() throws Exception
{
ByteArrayOutputStream byteOutput = new ByteArrayOutputStream();
DataOutput out = new DataOutputStream(byteOutput);
CustomObj original = new CustomObj("originalValue");
original.write(out);
CustomObj deserialized = new CustomObj("you should really use add a zero arg constructor as well");
DataInput in = new DataInputStream(new ByteArrayInputStream(byteOutput.toByteArray()));
deserialized.readFields(in);
Assert.assertEquals(original.value, deserialized.value);
}
}