Reputation: 391
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.
Upvotes: 0
Views: 2176
Reputation: 1419
You should get an IOException
if the file is "in use" So you can try this:
(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.
Upvotes: 1
Reputation: 1406
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:
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. Your test case which checks for IOexception from your method will look somewhat like this:
@Test(expected=IOException.class)
public void shouldReadPostParamsThrowIOExceptionIfInvalidRead(){
}
Upvotes: 0