gpt4 book ai didi

java - 如何为此 "FileNotFoundException"编写 Junit 测试

转载 作者:行者123 更新时间:2023-11-29 04:09:00 26 4
gpt4 key购买 nike

我如何为 FileNotFoundException 编写 Junit 测试,我是否需要在测试中做一些事情以便看不到我的“numbers.txt”文件?

public void readList() {
Scanner scanner = null;
try {
scanner = new Scanner(new File("numbers.txt"));

while (scanner.hasNextInt()) {
final int i = scanner.nextInt();
ListOfNumbers.LOGGER.info("{}", i);


}
} catch (final FileNotFoundException e) {
ListOfNumbers.LOGGER.info("{}","FileNotFoundException: " + e.getMessage());
} finally {
if (scanner != null) {
ListOfNumbers.LOGGER.info("{}","Closing PrintReader");
scanner.close();
} else {
ListOfNumbers.LOGGER.info("{}","PrintReader not open");
}
}

}

最佳答案

实际上,您打算做的是测试 JVM 本身,以查看在特定条件下是否会抛出适当的异常。有人争辩说,这不再是单元测试了,您需要假设外部 JMV 方面的内容可以正常工作,不需要进行测试。

您的方法 readList() 是高度不可测试的。您想编写一个文件存在性测试,但您在该方法中创建了一个文件对象而不是注入(inject)它。您想查看是否抛出异常,但您在该方法中捕获了它。

让我们具体化:

public void readList(File inputFile) throws FileNotFoundException {
//... do your code logic here ...
}

然后您可以在单元测试中使用名为 ExpectedException 的 JUnit @Rule:

@RunWith(MockitoJUnitRunner.class)
public class ReaderTest {

@Rule
public ExpectedException exception = ExpectedException.none(); // has to be public

private YourReader subject = new YourReader();

@Test(expect = FileNotFoundException.class)
public void shouldThrowFNFException() {
// given
File nonExistingFile = new File("blabla.txt");

// when
subject.readList(nonExistingFile);
}

// ... OR ...

@Test
public void shouldThrowFNFExceptionWithProperMessage() {
// given
File nonExistingFile = new File("blabla.txt");

exception.expect(FileNotFoundException.class);
exception.exceptionMessage("your message here");

// when
subject.readList(nonExistingFile);
}
}

关于java - 如何为此 "FileNotFoundException"编写 Junit 测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56267871/

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