-1

I have Java program which fetches HTML from a website. It displays the content on console and then saves it to a file named web_content.txt. How do I write a test case for this?

My Program is:

public class UrlDown {
   public static void main(String[] args) throws Exception {
      UrlDown down = new UrlDown();
      File f = new File("web_content.txt");
      String loc = "http://www.google.com";
      down.saveUrlToFile(f, loc);

   }

   public void saveUrlToFile(File saveFile, String location) {
      URL url;
      try {
         url = new URL(location);
         BufferedReader in = new BufferedReader(new InputStreamReader(
               url.openStream()));
         BufferedWriter out = new BufferedWriter(new FileWriter(saveFile));

         char[] cbuf = new char[255];
         StringBuilder builder = new StringBuilder();
         while ((in.read(cbuf)) != -1) {
            out.write(cbuf);
            builder.append(cbuf);
         }
         String downloaded = builder.toString();
         System.out.println();
         System.out.println(downloaded);
         in.close();
         out.close();

      } catch (MalformedURLException e) {
         e.printStackTrace();
      } catch (IOException e) {
         e.printStackTrace();
      }
   }
}
Perception
  • 79,279
  • 19
  • 185
  • 195
Sanjay Verma
  • 331
  • 1
  • 3
  • 15

3 Answers3

1

Don't reinvent the square wheel. Just use some lib.

For example FileUtils from apache-commons - http://commons.apache.org/io/apidocs/org/apache/commons/io/FileUtils.html#copyURLToFile(java.net.URL, java.io.File)

Kiril Kirilov
  • 11,167
  • 5
  • 49
  • 74
0

If you are on Java 7, you can use the Files.copy() method to save the content of a InputStreamto a file.

To verify that this is working you can use the TemporaryFolder from jUnit to verify that you get the location correct, see https://stackoverflow.com/a/6185359/303598

Community
  • 1
  • 1
matsev
  • 32,104
  • 16
  • 121
  • 156
0

Have your unit test setup a mock http server (google will give you plenty of info). Pass in a url and check the file contains the expected content

vickirk
  • 3,979
  • 2
  • 22
  • 37