mardi 15 octobre 2019

How to test IO exceptions?

There is a WriterReader object in my code which uses FileOutputStream and ObjectOutputStream. Therefore writing an object to a file throws IO exceptions. I am trying a way to handle FileNotFound exception and throw other IO exceptions. Also while handling FileNotFound exception, I want to test it with JUnit 5.

I tried the following test, using date as a unique file name, asserting that file DNE, then writing the object to a file that DNE, which SHOULD trigger FileNotFound exception. And while handling that exception, I basically create a new file with the same name, also creating dirs before that.

Code:

@Test
void testWriteReadObjectFileNotFound() {
    String timeStamp = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
    File file = new File("data\\test\\" + timeStamp );
    try {
        assertFalse(file.exists());
        System.out.println(file.exists());
        String s1 = "testObj";
        wr.writeObject(s1, file.getName());
        String s2 = (String) wr.readObject(file.getName());
        assertEquals("testObj", s2);
        assertTrue(file.exists());
    } catch (IOException e) {
        fail();
    } catch (ClassNotFoundException e) {
        fail();
    }
    file.delete();
}

//MODIFIES: file at filepath
//EFFECTS: Writes given object to file
public void writeObject(Object serObj, String fileName) throws IOException {
    FileOutputStream fileOut;
    ObjectOutputStream objectOut;
    try {
        new FileOutputStream(filepath + fileName);
    } catch (FileNotFoundException e) {
        File file = new File(filepath + fileName);
        file.getParentFile().mkdirs();
        file.createNewFile();
    } finally {
        fileOut = new FileOutputStream(filepath + fileName);
        objectOut = new ObjectOutputStream(fileOut);
        objectOut.writeObject(serObj);
        objectOut.close();
    }
}

But in my code coverage it shows that the lines :

catch (FileNotFoundException e) {
        File file = new File(filepath + fileName);
        file.getParentFile().mkdirs();
        file.createNewFile();

is not covered. Can one explain me this situation?

Aucun commentaire:

Enregistrer un commentaire