Search code examples
androidmockitopowermockito

How to execute the failure scenario for the catch block of the method


Below is the code for which I want to write the test case ,

   public static void createFileAndSave(String tag, String logText, File logFile) {
            try (BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(logFile, true))) {
                bufferedWriter.write(getCurrentDate() + "   " + tag + "   " + logText + "\r\n");
                bufferedWriter.newLine();
            } catch (NullPointerException | IOException ex) {
                Log.e(TAG, "Couldn't write the file  = " + ex.getMessage());
            }
        }

And I have written the test cases for it , as goes in the catch block of the actuall method but in catch block when I debug ex.getMessage come as null.

 @Test
public void testWriteToFileException() {
    File file  = mock(File.class);
    try {
        when(file.getAbsolutePath()).thenReturn("/data/user/0/logs/logs.txt");
        when(file.exists()).thenReturn(true);
        Logger.createFileAndSave("text", "text" ,file);
    } catch (Exception e) {
        assertTrue(e instanceof NullPointerException);
    }
}

Where "/data/user/0/logs/logs.txt" is the wrong path to throw an exception.

output : ex.getMessage() result come as null.

Can anyone suggest any better way to mock this?


Solution

  • If I add a throw Nullpointer exception in the catch block of the method createFileAndSave() then the catch block of the test cases will be executed.

    public static void createFileAndSave(String tag, String logText, File logFile) {
                try (BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(logFile, true))) {
                    bufferedWriter.write(getCurrentDate() + "   " + tag + "   " + logText + "\r\n");
                    bufferedWriter.newLine();
                } catch (NullPointerException | IOException ex) {
                    throws(NullPointerException);
                }
            }