Integration test for image download java

2020-07-29 17:20发布

问题:

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.