测试方法还是try-catch?
我希望有人能告诉我通过 junit4 测试代码时遇到的场景的最佳实践。
我的伪代码如下:
public class TestClass {
private String readFromFile(String filePath) {
use BufferedReader, get content file input
append BufferedReader to StringBuffer
return string
}
@Test
public void testMethodOne() {
String s = readFromFile(C:\fileOne);
doStuff(s);
}
}
我遇到的问题是 BufferedReader 可以抛出 IOException。如果 readFromFile() 方法不是我正在分类的测试中的方法(我只需要它用于这些测试场景),我是否用 @Test (expected = IOException.class)
注释它,或者我应该使用 try-catch 块?
非常感谢!
I was hoping that someone could tell me the best practice for the scenario I am running into with testing my code via junit4.
My pseudocode is as follows:
public class TestClass {
private String readFromFile(String filePath) {
use BufferedReader, get content file input
append BufferedReader to StringBuffer
return string
}
@Test
public void testMethodOne() {
String s = readFromFile(C:\fileOne);
doStuff(s);
}
}
The issue that I am having is that BufferedReader can throw an IOException. If the readFromFile() method is not a method in the test I am classing (I only need it for these test scenarios), do I annotate it with @Test (expected = IOException.class)
anyway, or should I use a try-catch block?
Thank you very much!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果它抛出异常并且您没有预料到它会抛出异常,那么这是一种异常情况。如果无法读取文件并且无法执行测试,则这是一个错误,与测试本身无关。
将
throws
添加到readFromFile
方法以及使用它的测试方法中。If it throws an exception and you're not expecting it to, then it's an exceptional situation. If the file cannot be read and the test cannot be performed, it's an error, it's not something related to the tests themselves.
Add
throws
to thereadFromFile
method and to the test methods using it.