gordonad / powermock

Automatically exported from code.google.com/p/powermock
0 stars 0 forks source link

How to do: Mocking java.io exception #136

Closed GoogleCodeExporter closed 8 years ago

GoogleCodeExporter commented 8 years ago
I am trying to mock java.io.FileNotFoundException and java.io.IOException 
in the below function.

class Util {
public static String readFileIntoBuffer(final String filename) {
        StringBuffer buffer = new StringBuffer();
        BufferedReader in = null;
        FileReader f = null;
        try {
            f = new FileReader(filename);
            in = new BufferedReader(f);

            String str;
            while((str = in.readLine()) != null) {
                buffer.append(str);
            }
            f.close();
            f= null;
            in.close();
            in = null;
        }catch (FileNotFoundException e)
        {
            log.severe("FileNotFoundException:Failed to read file:" +
filename );

        }
        catch (IOException e)
        {
            log.severe("IOException:Failed to read file:" + filename );

        }
        finally
        {
            try
            {
                if(f != null)
                    f.close();
                if(in != null)
                    in.close();
            }
            catch (Exception ex)
            {
            }

        }
        return buffer.toString();
    }
}

Unit test case:
@Test
    public void testreadFileIntoBuffer_FileNotFoundException() throws
Exception {
        System.out.println("getreadFileIntoBuffer_FileNotFoundException");
        FileReader f = PowerMock.createMock(FileReader.class);
        PowerMock.expectNew(FileReader.class, Config.MAF_MSG).andThrow(new
java.io.FileNotFoundException("FileNotFoundException"));
        PowerMock.replay(f, FileReader.class);
        PowerMock.expectNew(BufferedReader.class, f).andThrow(new
java.io.FileNotFoundException("FileNotFoundException")); 
        PowerMock.replay(BufferedReader.class);

        String result =
                Util.readFileIntoBuffer(Config.MAF_MSG);
        assertEquals("", result);
        PowerMock.verify(FileReader.class);
    }

What I am missing?

Original issue reported on code.google.com by rohit.c.joshi@gmail.com on 31 Jul 2009 at 4:02

GoogleCodeExporter commented 8 years ago
See post in the mailing list, this is most likely not a bug.

Original comment by johan.ha...@gmail.com on 31 Jul 2009 at 6:18