Integration test for image download java

点点圈 提交于 2019-12-06 15:59:59

问题


I'm trying to write an integration test to see if a file is downloaded correctly from a url. I'm not sure how to test this because I expect to get the file in byte[] but I not really sure about the image that I'm comparing it to. I thought about downloading the file manually and then convert it to bytes and take the result and paste it in the code as the expected value and than compare it to the result i get. If you have a better idea I would be glad to hear it.

Thanks:)


回答1:


Comparing the images' hash value will be helpful.

  1. Compute the hash value before and after downloading the file.
  2. Compare the hash values. If they are equal, your file's integrity is good.

You can use hash algorithms like MD5 or SHA-1. If the files are smaller MD5 is good. For large number of file comparison SHA-1 will be useful since there will be less collisions.




回答2:


Since you are using and

expect to get the file in byte[]

There's an input stream decorator, java.security.DigestInputStream or java.security.MessageDigest, so that you can compute the digest while using the input stream.

import java.io.*;
import java.security.MessageDigest;

public class MD5Checksum {

   public static byte[] createChecksum(String filename) throws Exception {
       InputStream fis =  new FileInputStream(filename);

       byte[] buffer = new byte[1024];
       MessageDigest complete = MessageDigest.getInstance("MD5");
       int numRead;

       do {
           numRead = fis.read(buffer);
           if (numRead > 0) {
               complete.update(buffer, 0, numRead);
           }
       } while (numRead != -1);

       fis.close();
       return complete.digest();
   }

   public static String getMD5Checksum(String filename) throws Exception {
       byte[] b = createChecksum(filename);
       String result = "";

       for (int i=0; i < b.length; i++) {
           result += Integer.toString( ( b[i] & 0xff ) + 0x100, 16).substring( 1 );
       }
       return result;
   }

   public static void main(String args[]) {
       try {
           System.out.println(getMD5Checksum("apache-tomcat-5.5.17.exe"));               
       }
       catch (Exception e) {
           e.printStackTrace();
       }
   }
}

Here you can find other also good code snippets.



来源:https://stackoverflow.com/questions/26630587/integration-test-for-image-download-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!