JUnit - NoSuchElementException:找不到行

时间:2017-08-12 18:30:17

标签: java maven junit java.util.scanner

我正在尝试学习单元测试和Maven,为此我使用JUnit并编写简单的随机名称生成器。我有以下课程:

public class Database {

  public String readRandomName(String url) throws FileNotFoundException {
     int sum = calculateFileLines(url);
     int lines = (int) (Math.random()*sum);
     File file = new File(url);
     Scanner scanner = new Scanner(file);
     for (int i=0; i<lines;i++){
         scanner.nextLine();
     }
     return scanner.nextLine();
  }

  public int calculateFileLines(String url) throws FileNotFoundException {
    int sum = 0;
    try (Scanner scanner = new Scanner(new File(url))){
        while(scanner.hasNextLine() && scanner.nextLine().length()!=0){
            ++sum;
        }
    }
    return sum;
  }
}

当我像这样进行简单的测试时:

public static void main(String[] args) throws FileNotFoundException {
    Database database = new Database();
    database.readRandomName("names/maleNamesPL.txt");
}

它完美无缺,但是当我尝试使用断言编写JUnit测试时,出现意外故障,我不明白。这是测试代码:

@Test
public void readRandomNameTest() throws FileNotFoundException {
    Database database = new Database();
    Assert.assertNotNull("Should be some name", database.readRandomName("names/maleNamesPL.txt"));
}

结果:

Tests in error: 
readRandomNameTest(DatabaseTest): No line found

感谢您的帮助,谢谢!

1 个答案:

答案 0 :(得分:1)

你正在调用nextLine()并且当没有行时它会抛出异常,就像javadoc所描述的那样。它永远不会返回null

http://download.oracle.com/javase/1,5.0/docs/api/java/util/Scanner.html

使用Scanner,您需要检查下一行是否有hasNextLine()

所以循环变为

while(scanner.hasNextLine()){
    String str=scanner.nextline();
    //...
}