gpt4 book ai didi

java - 字符串序列化单元测试失败

转载 作者:行者123 更新时间:2023-12-01 19:50:04 24 4
gpt4 key购买 nike

String 序列化运行 Junit 测试后,它失败并给出了以下结果:

预期:“netmodel”
实际:“l”

序列化方法如下

public static void serializeString(String objectToSerialize, OutputStream outputStream) {
byte[] bytesArr = objectToSerialize.getBytes();
serializeInt(bytesArr.length, outputStream);
try {

outputStream.write(bytesArr);
} catch (IOException e) {
e.printStackTrace();
}
}

我的反序列化方法如下

public static String deserializeString(InputStream inputStream) {
String deserializeObject = "";
char asciiToChar;
int stringByteArrayLength = deserializeInt(inputStream);
byte[] databytesArr = new byte[stringByteArrayLength];

try {
inputStream.read(databytesArr, 0, stringByteArrayLength);
}
catch (IOException e) {
e.printStackTrace();
}

for (int i = 0; i < databytesArr.length; i++) {
asciiToChar = (char) databytesArr[i];
deserializeObject = "" + Character.toString(asciiToChar);
}
return deserializeObject;
}

最后我写了一个单元测试如下

public class StringSerializerTest {

private InputStream iStream;
private ByteArrayOutputStream oStream;

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

String serialzeAndDeserializeObject(String stringValue) {
OutputStreamUtil.serializeString(stringValue, oStream);
iStream = new ByteArrayInputStream(oStream.toByteArray());
return InputStreamUtil.deserializeString(iStream);
}

@Test
public void equals_equal() {
String stringValue = "netmodel";
String deserializedStringValue = serialzeAndDeserializeObject(stringValue);
assertThat(deserializedStringValue).isEqualTo(stringValue);
}
}

出了什么问题?以及如何修复它?

最佳答案

您将在每次迭代期间重新分配 deserializeObject 的整个值

for (int i = 0; i < databytesArr.length; i++) {
asciiToChar = (char) databytesArr[i];
deserializeObject = "" + Character.toString(asciiToChar);
}

这会导致仅最后一个字符(在本例中为 l)存储在 deserializeObject 中。此循环应附加下一个字符到deserializeObject,如下所示:

for (int i = 0; i < databytesArr.length; i++) {
asciiToChar = (char) databytesArr[i];
deserializeObject += Character.toString(asciiToChar);
}

更正后的反序列化逻辑为:

public static String deserializeString(InputStream inputStream) {
String deserializeObject = "";
char asciiToChar;
int stringByteArrayLength = deserializeInt(inputStream);
byte[] databytesArr = new byte[stringByteArrayLength];

try {
inputStream.read(databytesArr, 0, stringByteArrayLength);
}
catch (IOException e) {
e.printStackTrace();
}

for (int i = 0; i < databytesArr.length; i++) {
asciiToChar = (char) databytesArr[i];
deserializeObject += Character.toString(asciiToChar);
}
return deserializeObject;
}

关于java - 字符串序列化单元测试失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51632922/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com