如何执行方法的 catch 块的失败场景

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

下面是我要编写测试用例的代码,

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

并且我已经为它编写了测试用例,就像在实际方法的 catch 块中一样,但在我调试时的 catch 块中 ex.getMessage 为 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);
    }
}

其中“/data/user/0/logs/logs.txt”是抛出异常的错误路径

输出:ex.getMessage() 结果为空。

谁能提出更好的模拟方法?

如果我在方法 createFileAndSave() 的 catch 块中添加一个 throw Nullpointer 异常,那么将执行测试用例的 catch 块。

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);
            }
        }