在JUnit中捕获IOException

问题描述

我想就如何在我的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测试中创建错误的路径才能引发该异常,但是我无法获得所需的结果。我对此表示感谢。谢谢。

解决方法

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

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

创建BufferedWriter绝不会抛出IOException,这意味着该断言将始终失败:

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

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

,

调用FROM python:3.7-alpine LABEL author= APPLE LABEL company= PINEAPPLE ARG HOME_DIR='/schooldata' ADD . $HOME_DIRECT ##[ this line ] EXPOSE 5000 WORKDIR $HOME_DIRECT RUN pip install -r requirements.txt ENTRYPOINT ["python","app.py"] 测试标准库是没有意义的。实际上,您应该调用Assertions.assertThrows(IOException.class,() -> new BufferedWriter(bw));来测试自己的方法。

无法获得异常的原因是Assertions.assertThrows(IOException.class,() -> logger.LogHostStream("logText"));永远不会引发任何异常。引发异常的地方是() -> new BufferedWriter(bw));

如果要测试您的方法以检查其是否抛出异常,则应删除try-catch块,如下所示:

FileWriter fWriter = new FileWriter(logFileName,true);

由于一旦捕获到异常,便无法使用FileWriter fw = new FileWriter(fileName,true); BufferedWriter bw = new BufferedWriter(fw); bw.write(outText);

检查该异常

之后,您应该将Assertions.assertThrows中的/config/log/host_logs的值更改为无效的路径值。然后调用ocomw_config.xml ,您将看到例外的异常。