【问题标题】:Need to write JUnit Test case需要编写 JUnit 测试用例
【发布时间】:2016-01-20 03:26:09
【问题描述】:

我是一名较新的 Java 开发人员。 但是我对编写Junit测试用例知之甚少。 我很快就要参加工作考试了。 他们希望我为此编写一个程序

  1. 要从任何网站读取 HTML,请说“http://www.google.com”(您 可以使用 Java 中内置 API 的任何 API,例如 URLConnection )
  2. 在控制台打印来自上述 url 的 HTML 并将其保存到一个文件 ( web-content.txt) 在本地机器中。
  3. 以上的 JUnit 测试用例 计划。

我已经完成了如下前两个步骤:

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());
    }
  }
}    

现在我需要第三步的帮助。

【问题讨论】:

  • Google JUnit tutorial 看看你能找到什么。
  • 您首先需要将您的方法分解为可测试的更小方法。
  • 到目前为止,我已经在 Google 上搜索了 junit 教程,了解了一些关于如何为基本程序(如加法/减法)编写 junit 测试用例的知识。我仍然找不到太多帮助来为我的这个程序编写 junit 测试用例。 @mauhiz:你能告诉我应该打破和测试哪种方法以及如何测试?
  • @Ryan Malhotra ,您走在正确的轨道上,始终尝试遵循编程中的功能块,这将有助于很多场景,所以现在如果您这样做,那将是非常简单的一个做junits测试用例
  • . Still i cant find much help to write junit test cases 。问问自己:这个功能之后我应该期待什么?我不应该期待什么?我可以对不同场景下每个函数的所有可能输入进行分组吗?

标签: java junit


【解决方案1】:

你需要像这样提取一个方法

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);
        }
    }
}

好的,现在您可以编写 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"));

    }
  }

【讨论】:

  • 但是你能详细说明一下这条线的实际作用吗? ' assertTrue(baos.toString().contains("google"));'
  • 我认为它只是检查提取的 html 是否有字符串“google”。在这种情况下我还能测试什么?
  • 嗯,单元测试确实测试了代码的原始功能。代码什么也不做!因此,如果不重复、过时或简陋的代码,你就不能编写更多的测试。
【解决方案2】:
  • 首先将代码从 main 方法移动到 JavaSourceViewer。
  • 第二次让这些方法返回一些 你可以测试。例如输出文件或 Reader 的文件名。

然后为单元测试创​​建一个类

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");
      ....
   }

}

要执行 Junit,请使用 IDE(如 eclipse)或将 junit.jar 文件放在类路径中并从控制台:

java org.junit.runner.JUnitCore JavaSourceViewerTest

【讨论】:

    【解决方案3】:

    你的步骤不对。这样做肯定会有所帮助,3,然后是 1,然后是 2。这样做会迫使您从功能和单元的角度进行思考。结果代码将是可测试的,无需做任何特别的事情。除了为您提供安全网之外,先测试还指导您的系统设计。

    P.S. 切勿在测试前尝试编写代码。如您所见,这既不自然,也没有太大价值

    现在,为了测试第一个单元,您可以将stringgoogle.com 中的html 与一些现有的string 进行比较。但是如果谷歌改变它的页面,这个测试用例就会中断。另一种方法是只检查标头中的 HTTP 代码,如果是 200,那你就可以了。只是一个想法。

    对于第二个,您可以通过读取文件将您从网页读取的string 与您写入文件的字符串进行比较。

    【讨论】:

      【解决方案4】:
              String str = "";
              URL oracle = new URL("http://www.google.com/");
              BufferedReader in = new BufferedReader(
              new InputStreamReader(oracle.openStream()));
              File file = new File("C:/Users/rohit/Desktop/rr1.txt");
              String inputLine;
              FileWriter fw = new FileWriter(file.getAbsoluteFile()); 
              BufferedWriter bw = new BufferedWriter(fw); 
              while ((inputLine = in.readLine()) != null) { 
              System.out.println(inputLine); 
              bw.write(inputLine); 
              } 
      
              bw.close(); 
              in.close(); 
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多