【问题标题】:How to execute the failure scenario for the catch block of the method方法的catch块如何执行失败场景
【发布时间】:2020-07-17 12:51:42
【问题描述】:

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

   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 块中那样,但是当我调试 ex.getMessage 时在 catch 块中为 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() 结果为空。

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

【问题讨论】:

  • 不清楚您的意思...您正在遇到异常。如果你不是,就没有什么可以打电话给getMessage()on

标签: android mockito powermockito


【解决方案1】:

如果我在 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);
            }
        }

【讨论】:

    猜你喜欢
    • 2019-02-27
    • 1970-01-01
    • 1970-01-01
    • 2020-06-11
    • 1970-01-01
    • 2015-11-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多