布尔型序列化和反序列化单元测试失败

时间:2018-08-01 05:59:06

标签: java serialization junit boolean

运行用于布尔类型序列化的Junit测试后,它总是失败,并且我的序列化方法的值true如下所示

public static void serializeBoolean(boolean objectToSerialize, OutputStream outputStream) {
   byte[] bytesArr = new byte[1];
   ByteBuffer.wrap(bytesArr).put((byte) (objectToSerialize ? 1 : 0));
   try {
   outputStream.write(bytesArr);
   } catch (IOException e) {
   e.printStackTrace();
   }
}

我的反序列化方法如下

public static boolean deserializeBoolean(InputStream inputStream) {
   byte[] databytesArr = new byte[1];
   if (ByteBuffer.wrap(databytesArr).get() == 1) {
   return true;
   }
   else {
   return false;
   }
}

最后,我编写了如下的单元测试

public class BooleanSerializerTest {

  private InputStream iStream;
  private ByteArrayOutputStream oStream;

@Before
public void init() {
  oStream = new ByteArrayOutputStream();
 }

  boolean serialzeAndDeserializeObject(boolean booleanValue) {
  OutputStreamUtil.serializeBoolean(booleanValue, oStream);
  iStream = new ByteArrayInputStream(oStream.toByteArray());
  return InputStreamUtil.deserializeBoolean(iStream);
}

@Test
public void equalToTrue() {
  boolean booleanValue = true;
  boolean deserializedBooleanValue = 
  serialzeAndDeserializeObject(booleanValue);
  assertThat(deserializedBooleanValue).isEqualTo(booleanValue);
}

@Test
public void equalToFalse() {
  boolean booleanValue = false;
  boolean deserializedBooleanValue = 
  serialzeAndDeserializeObject(booleanValue);
  assertThat(deserializedBooleanValue).isEqualTo(booleanValue);
  }
}

equalToFalse()测试成功,但equalToTrue()始终失败

怎么了?以及如何解决?

2 个答案:

答案 0 :(得分:2)

您应该在方法inputStream.read(databytesArr);中添加deserializeBoolean,如下所示:

    public static boolean deserializeBoolean(InputStream inputStream) {
        byte[] databytesArr = new byte[1];
        try {
            inputStream.read(databytesArr);
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (ByteBuffer.wrap(databytesArr).get() == 1) {
            return true;
        } else {
            return false;
        }
    }

答案 1 :(得分:2)

由于未使用输入参数inputStream,因此您总是得到相同的结果,因此更新deserializeBoolean方法如下:

public static boolean deserializeBoolean(InputStream inputStream) throws IOException {
    byte[] databytesArr = new byte[1];
    inputStream.read(databytesArr);
    return ByteBuffer.wrap(databytesArr).get() == 1;
}

此后测试将成功。