在比较两个 bytearrayinputstream 时,我面临以下给定函数的以下错误
代码在这里
@Test
public void fileIsSame() throws IOException, InvalidEndpointException, InvalidPortException, InvalidKeyException, InvalidBucketNameException, NoSuchAlgorithmException, InsufficientDataException, NoResponseException, ErrorResponseException, InternalException, InvalidArgumentException, XmlPullParserException {
FileInputStream file = new FileInputStream("/Users/gauris/Documents/samplephoto/pexels-photo-46710.jpeg");
String fileName = "pexels-photo-46710.jpeg";
ByteArrayInputStream uploadByteArrayInputStream = new ByteArrayInputStream(file.toString().getBytes());
minioClient.putObject(bucketName, fileName, uploadByteArrayInputStream, uploadByteArrayInputStream.available(), "application/octet-stream");
String actualresult = IOUtils.toString(uploadByteArrayInputStream, StandardCharsets.UTF_8);
InputStream stream = minioClient.getObject(bucketName, fileName);
byte currentXMLBytes[] = stream.toString().getBytes(); //convert inputStream to byteArrayInputStream;
ByteArrayInputStream byteInputStream = new ByteArrayInputStream(currentXMLBytes);
String Expectedresult = IOUtils.toString(stream, StandardCharsets.UTF_8);
System.out.println("expected: "+Expectedresult);
System.out.println("actual: "+ actualresult);
//Arrays.equals((uploadByteArrayInputStream).toByteArray(), (byteInputStream).toByteArray());
assertEquals(byteInputStream.toString(), uploadByteArrayInputStream.toString());
uploadByteArrayInputStream.close();
stream.close();
}
错误
org.junit.ComparisonFailure: expected:<...yteArrayInputStream@[43195e57]> but was:<...yteArrayInputStream@[333291e3]>
at org.junit.Assert.assertEquals(Assert.java:115)
at org.junit.Assert.assertEquals(Assert.java:144)
最佳答案
To String 方法打印给定对象的人类可读表示,而不是流的内容。您必须首先从 Streams 中获取字符串,然后对它们进行比较。
如果您使用 Java 9,则可以,
new String(input.readAllBytes(), StandardCharsets.UTF_8);
或者老方法,
ByteArrayOutputStream result = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int length;
while ((length = inputStream.read(buffer)) != -1) {
result.write(buffer, 0, length);
}
// StandardCharsets.UTF_8.name() > JDK 7
return result.toString("UTF-8");
然后您可以比较字符串。
关于java - 如何在junit测试中比较两个bytearrayinputstream?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50392640/