简体   繁体   中英

How to test IOException for a JSONObject?

I have the code below:

public static void writeJson(JSONObject outputFinal) throws IOException {
    fw.write(outputFinal.toString(3));
    fw.flush();
    fw.close();
}

I am trying to write a JUnit test to test the IOException. How can I make the JSONObject passed as a param trigger an exception?

Does the JSONObject need to cause the exception, or do you just need one from that method? You haven't specified what sort of JSONObject it is (which library), but a quick search showed one that throws a JSONException, which is not a subclass of IOException, so it wont be possible to cause it using the toString(3) method.

You haven't said how fw is created or whether you have access to it in the test. Assuming fw is an implementation of java.io.Writer , you can cause an exception to be thrown by ensuring it is closed before the call to writeJson .

If you can get access to fw in the test method just call fw.close() before calling writeJson and you will get a java.io.IOException: Stream closed

basically ,it's impossible to make the JSONObject passed as a param trigger an IOException,the IO error is not about what you write in the file.usually it occurs because the stream error or the file access authority issues of the current user. so I think you may try to edit the permissions of the file you want to write(denied everyone to access),then when you run your codes, an java.io.FileNotFoundException will occur,which is the subclass of IOException. Hope this helps.

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