java - 如何在junit测试中比较两个bytearrayinputstream?

标签 java unit-testing spring-boot

在比较两个 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/

相关文章:

java - 无法为单元测试创​​建属性实例

java - 为什么 Spring 存储库的 save() 有时会保存不相关的实体?

带有加密 JWT 访问 token 的 Spring Boot OAuth2

java - 无法使用 PowerMockito 模拟系统类静态方法

java - 在 IntelliJ IDEA 中显示 Maven/Sbt 托管项目的 JavaDoc/ScalaDoc

xcode - NSURL 书签在 Xcode Server 上的单元测试中失败

ios - UI : iOS 中动态数据的 UI 单元测试失败

java - Apache FOP - 有没有办法以编程方式嵌入字体?

java.lang.NoSuchMethodError : javax. persistence.JoinTable.indexes()[Ljavax/persistence/Index;

java - Spring Boot JPA向MySQL插入实体/对象时如何自动插入外键