Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Need to write JUnit Test case

Tags:

java

junit

I am a fresher java developer. But I dont have much knowledge about writing Junit test cases. I am going to have a job test soon. For which they want me to write a program

  1. To read HTML from any website say "http://www.google.com" ( You can use any API of inbuilt APIs in Java like URLConnection )
  2. Print on console the HTML from the url above and save it to a file ( web-content.txt) in local machine.
  3. JUnit test cases for above programme.

I have completed the first two steps as below:

import java.io.*;
import java.net.*;

public class JavaSourceViewer{
  public static void main (String[] args) throws IOException{
    System.out.print("Enter url of local for viewing html source code: ");
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    String url = br.readLine();
    try {
      URL u = new URL(url);
      HttpURLConnection uc = (HttpURLConnection) u.openConnection();
      int code = uc.getResponseCode();
      String response = uc.getResponseMessage();
      System.out.println("HTTP/1.x " + code + " " + response);

      InputStream in = new BufferedInputStream(uc.getInputStream());
      Reader r = new InputStreamReader(in);
      int c;
      FileOutputStream fout=new FileOutputStream("D://web-content.txt");
      while((c = r.read()) != -1){
        System.out.print((char)c);
        fout.write(c);
      }
      fout.close();
    } catch(MalformedURLException ex) {
      System.err.println(url + " is not a valid URL.");
    } catch (IOException ie) {
      System.out.println("Input/Output Error: " + ie.getMessage());
    }
  }
}    

Now I need help with 3rd step.

like image 643
Ryan Malhotra Avatar asked Sep 21 '12 08:09

Ryan Malhotra


3 Answers

You need to extract a method therefore like this

package abc.def;

import java.io.*;
import java.net.*;

public class JavaSourceViewer {
    public static void main(String[] args) throws IOException {
        System.out.print("Enter url of local for viewing html source code: ");
        BufferedReader br =
                new BufferedReader(new InputStreamReader(System.in));
        String url = br.readLine();
        try {
            FileOutputStream fout = new FileOutputStream("D://web-content.txt");
            writeURL2Stream(url, fout);
            fout.close();
        } catch (MalformedURLException ex) {
            System.err.println(url + " is not a valid URL.");
        } catch (IOException ie) {
            System.out.println("Input/Output Error: " + ie.getMessage());
        }
    }

    private static void writeURL2Stream(String url, OutputStream fout)
            throws MalformedURLException, IOException {
        URL u = new URL(url);
        HttpURLConnection uc = (HttpURLConnection) u.openConnection();
        int code = uc.getResponseCode();
        String response = uc.getResponseMessage();
        System.out.println("HTTP/1.x " + code + " " + response);

        InputStream in = new BufferedInputStream(uc.getInputStream());
        Reader r = new InputStreamReader(in);
        int c;

        while ((c = r.read()) != -1) {
            System.out.print((char) c);
            fout.write(c);
        }
    }
}

Ok, now you are able to write the JUnit-Test.

  package abc.def;

  import java.io.ByteArrayOutputStream;
  import java.io.IOException;
  import java.net.MalformedURLException;

  import org.junit.Test;

  import junit.framework.TestCase;

  public class MainTestCase extends TestCase {
    @Test
    public static void test() throws MalformedURLException, IOException{
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        JavaSourceViewer.writeURL2Stream("http://www.google.de", baos);
        assertTrue(baos.toString().contains("google"));

    }
  }
like image 91
Grim Avatar answered Nov 18 '22 00:11

Grim


  • First move your code from the main method to other methods in the JavaSourceViewer.
  • Second make these methods return something that you can test. e.g. the file name of the output file or the Reader.

Then create a class for the unit test

import org.junit.* ;
import static org.junit.Assert.* ;

public class JavaSourceViewerTest {

   @Test
   public void testJavaSourceViewer() {
      String url = "...";
      JavaSourceViewer jsv = new JavaSourceViewer();
      // call you methods here to parse the site
      jsv.xxxMethod(...)
      ....
      // call you checks here like: 
      // <file name to save to output data from your code, actual filename>  - e.g.
      assertEquals(jsv.getOutputFile(), "D://web-content.txt");
      ....
   }

}

To execute the Junit use an IDE (like eclipse) or put the junit.jar file in the classpath and from the console:

java org.junit.runner.JUnitCore JavaSourceViewerTest

like image 41
Makis Arvanitis Avatar answered Nov 17 '22 23:11

Makis Arvanitis


Your steps are not right. Doing it in this way would definitely help, 3, then 1, and then 2. Doing it this way will force you to think in terms of functionalities and units. And the result code will be testable, without doing anything special. Test first also guide the design of your system, besides providing you a safety net.

P.S. Never try to write the code before the test. It's simply not natural neither it gives much value, as you can see.

Now, to test the 1st unit, you can compare the string, the html from google.com, with some existing string. But that test case will break if Google changes it's page. Other way, is to just check the HTTP code from the header, if that's 200, you are fine. Just an idea.

For the second one, you can compare the string, you read from the web page, to string you wrote to the file, by reading the file.

like image 31
Adeel Ansari Avatar answered Nov 18 '22 00:11

Adeel Ansari