1

我对 JUnit 测试有疑问。

我正在尝试测试我的代码,但由于某种未知的原因,它一直让我失败。这是我尝试测试的代码:

public void userInputWord() throws Exception{ 
    System.out.println("****Please input your word, 2 to 8 ***");
    System.out.println("**********character strings.**********");
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    inputWord = br.readLine();
    setInputWord(inputWord);
    setWordLenght(inputWord.length());          
    System.out.println("***Please input amount of words you***");
    System.out.println("*************want to find*************");
    try{
        stringLadder = br.readLine();
        setLadder(Integer.parseInt(stringLadder));
    }catch(NumberFormatException nfe){
        System.out.println("Your input must be integer value.");
    }
    searchForMatch();
}

基本上这种方法是要求用户输入两个值(起始词和他想看到多少个词作为 WordLadder)我将这些值分配给设置方法。我的这个类的 JUnit 如下:

public void testUserInputWord() {
    Generation gener = new Generation();
    StringReader read = new StringReader("broom");
    Scanner scan = new Scanner(read);
    gener.setInputWord(scan.toString());
    assertEquals("broom", gener.getInputWord());
}

我以前从未写过 JUnit,只是做了一些研究,谁能解释我做错了什么?

4

2 回答 2

2

嗯,第一个问题是您永远不会调用您要测试的代码。您目前正在测试的只是 getter 和 setter(forladderinputWord)。

不幸的是,测试该userInputWord方法很棘手,因为它依赖于System.in. 您需要有一种“伪造”用户输入的方法。一种选择是使该方法采用 aScanner或 a Reader。然后,您可以通过 a 创建所有适当的用户输入StringReader,以便该方法读取您预先编程的数据。然后,您将测试结果。如果此类的其他部分也需要用户输入,您可能需要更改它,以便您的构造函数采用某些东西(同样,可能是 a Scanner,可能是 a Reader)来表示用户输入。同样,您将在构建测试实例时提供测试数据。

从根本上说,“提供用户输入的东西”的想法是您尝试测试的代码的依赖项 - 单元测试的许多技能正在研究如何提供受测试控制的依赖项。有很多方法适用于不同的情况 - 在这种情况下,您可能只使用现有的实现 ( StringReader) 作为底层数据源而不是控制台。

于 2012-10-26T05:49:14.597 回答
2

您说 JUnit 测试没有达到您的预期。也许您应该告诉我们您的期望究竟是什么,这样我们就可以告诉您为什么没有达到期望。

As Jon said, the code snippets you show us do not really belong together. Your test method seems to test the setInputWord / getInputWord pair of setter and getter. There is no call to userInputWord at all.

Also I can see that your test method is prefixed with test and does not have any annotation. This is the terribly outdated JUnit 3 style. Please have a look at the JUnit Cookbook.

于 2012-10-26T06:25:10.197 回答