简体   繁体   中英

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.

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(){
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM