如果我有一个实现Writable的自定义对象类,那么测试序列化/反序列化的最佳方法是使用mockito进行单元测试吗?我正在考虑创建模拟映射器/缩减器,但这似乎太不必要了。
示例代码:
public class CustomObj implements Writable {
private String value;
public CustomObj(String v) {
value = v;
}
@Override
public void write(DataOutput out) throws IOException {
out.writeChars(value);
}
public void readFields(DataInput in) throws IOException {
value = in.readLine();
}
答案 0 :(得分:3)
为什么要使用模拟框架?
往返测试将是最简单和最快的 - 所以只需序列化然后反序列化并比较两个实例。不要使用equals()方法进行比较,即使它经过了充分测试。
您还需要测试边缘,例如,为了确保在反序列化时重新创建/重新添加瞬态字段,您可以使用readResolve()
上找到一些有用的提示以下是往返测试示例:
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);
}
}