java在junit中捕获ioexception

7ivaypg9  于 2021-07-06  发布在  Java
关注(0)|答案(2)|浏览(485)

我想请求帮助我如何在junit测试中捕获ioexception,以测试我的代码在发生错误时是否抛出正确的异常。
这是我的主要代码:

public void LogHostStream(String v_strText) {

    Date dtToday = new Date();
    SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("MM-dd-yyyy HH:mm:ss");
    String date = DATE_FORMAT.format(dtToday);

    SimpleDateFormat FILE_DATE_FORMAT = new SimpleDateFormat("yyyyMMdd");
    String filedate = FILE_DATE_FORMAT.format(dtToday);

    IConfiguration cfgHandler = ConfigurationFactory.getConfigHandle();
    String logFileName = cfgHandler.GetXMLValue("config.xml", "/config/log/host_logs");

    String outText = String.format("%s \n %s \n", date, v_strText);
    String fileName = logFileName + "_" + filedate + ".txt";

    try (FileWriter fw = new FileWriter(fileName, true);
         BufferedWriter bw = new BufferedWriter(fw);) {
        bw.write(outText);
    } catch (IOException e) {
        e.printStackTrace();
    }

这是我的junit:

@Test(expected = IOException.class)
public void testLogHostStreamThrowsIOException() throws IOException {
    logger.LogHostStream("");
    String logFileName = cfgHandler.GetXMLValue("ocomw_config.xml", "/config/log/host_logs");
    FileWriter fWriter = new FileWriter(logFileName, true);
    BufferedWriter bw = new BufferedWriter(fWriter);

    Assertions.assertThrows(IOException.class, () -> new BufferedWriter(bw));    
}

我想我必须在我的junit测试中创建一个错误的路径来抛出这个异常,但是我没有得到我想要的结果。我很感谢你的帮助。谢谢。

mznpcxlj

mznpcxlj1#

打电话是没有意义的 Assertions.assertThrows(IOException.class, () -> new BufferedWriter(bw)); 测试标准库。事实上你应该打电话 Assertions.assertThrows(IOException.class, () -> logger.LogHostStream("logText")); 来测试你自己的方法。
你不能得到例外的原因是 () -> new BufferedWriter(bw)); 不会抛出任何异常。引发异常的位置是 FileWriter fWriter = new FileWriter(logFileName, true); 如果您想测试您的方法以检查它是否抛出excpeted异常,您应该删除try-catch块,如下所示:

FileWriter fw = new FileWriter(fileName, true);
BufferedWriter bw = new BufferedWriter(fw);
bw.write(outText);

因为一旦捕捉到异常,就不能用 Assertions.assertThrows 在此之后,您应该更改 /config/log/host_logsocomw_config.xml 无效的路径值。那就打电话 Assertions.assertThrows(IOException.class, () -> logger.LogHostStream("someLogText")); ,您将看到例外情况。

jgzswidk

jgzswidk2#

FileWriter 当无法创建或打开文件进行写入时,将引发异常。实现这种情况的一种方法是确保文件应该位于的目录不存在。此测试成功:

@Test
void testThrows() throws IOException {
    assertThrows(IOException.class, () -> new FileWriter("/no/such/place"));
}

创建 BufferedWriter 永远不会扔垃圾 IOException ,这意味着此Assert将始终失败:

assertThrows(IOException.class, () -> new BufferedWriter(bw));

你不应该为我写测试 FileWriter 以及 BufferedWriter 不过:它们是经过良好测试的标准库类,您可以相信它们按指定的方式工作。

相关问题