[英]JUnit force BufferedReader to throw IOException
I have following method 我有以下方法
public static String readPostParams(Request request, String param) {
BufferedReader br = new BufferedReader(new InputStreamReader(request.getBodyAsStream()));
String line;
try {
while ((line = br.readLine()) != null) {
if (line.contains(param)) {
//System.out.println("---> " + param + " :" + getValue(line));
return getValue(line);
}
}
} catch (IOException ex) {
// Ignore
}
return "";
}
I want a JUnit Unit test to force BufferedReader to throw IOException so I can cover that part also. 我想要一个JUnit单元测试来强制BufferedReader抛出IOException,因此我也可以介绍该部分。
If you want to test this method for IOException , you should propagate the exception to the calling method by removing the try catch block and adding the throws clause to your method: 如果要测试此方法的IOException ,应通过删除try catch块并将throws子句添加到方法中, 将异常传播到调用方法:
public static String readPostParams(Request request, String param) throws IOException;
There is an attribute called as 'expected' for the @Test annotation which you can use to check for exceptions. @Test注释有一个称为“ expected”的属性,您可以使用该属性检查异常。 Your test case which checks for IOexception from your method will look somewhat like this:
从您的方法检查IOexception的测试用例将看起来像这样:
@Test(expected=IOException.class)
public void shouldReadPostParamsThrowIOExceptionIfInvalidRead(){
}
You should get an IOException
if the file is "in use" So you can try this: 如果文件“正在使用”,则应该得到
IOException
,因此您可以尝试以下操作:
(I have never tested this) (我从未测试过)
In you test use 在您测试使用
final RandomAccessFile lockFile = new RandomAccessFile(fileName, "rw");
lockFile.getChannel().lock();
Then call your method from above and unlock the file once you are done. 然后从上方调用您的方法,并在完成后将文件解锁。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.