gpt4 book ai didi

java - JUnit-NoSuchElementException : No line found

转载 作者:行者123 更新时间:2023-12-02 12:22:46 28 4
gpt4 key购买 nike

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

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

非常感谢您的帮助,谢谢!

最佳答案

您正在调用 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();
//...
}

关于java - JUnit-NoSuchElementException : No line found,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45653605/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com