简体   繁体   English

在 JUnit 捕获 IOException

[英]Catching IOException in JUnit

I would like to ask for help on how am I be able to catch IOException on my JUnit testing just to test if my code will throw the right exception once error occured.我想寻求帮助,了解我如何能够在我的 JUnit 测试中捕获 IOException,只是为了测试我的代码是否会在发生错误时抛出正确的异常。

Here is my main code:这是我的主要代码:

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

And here is my JUnit:这是我的 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));    
}

I think I have to create a wrong path on my JUnit test to throw that exception, but I was not able to get the result I want.我想我必须在我的 JUnit 测试中创建一条错误的路径才能抛出该异常,但我无法获得我想要的结果。 I appreciate any help for this.感谢您为此提供的任何帮助。 Thanks.谢谢。

FileWriter will throw an exception when it cannot create or open the file for writing. FileWriter在无法创建或打开文件进行写入时将抛出异常。 One way to make this happen is making sure the directory the file is supposed to be in does not exist.实现此目的的一种方法是确保文件应该位于的目录不存在。 This test succeeds:此测试成功:

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

Creating a BufferedWriter will never throw an IOException , which means this assertion will always fail:创建BufferedWriter永远不会抛出IOException ,这意味着这个断言总是会失败:

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

You shouldn't write tests for FileWriter and BufferedWriter though: they are well tested standard library classes and you can trust that they work as specified.不过,您不应该为FileWriterBufferedWriter编写测试:它们是经过良好测试的标准库类,您可以相信它们会按规定工作。

It is meaningless to call Assertions.assertThrows(IOException.class, () -> new BufferedWriter(bw));调用Assertions.assertThrows(IOException.class, () -> new BufferedWriter(bw)); to test standard library.测试标准库。 In fact you should call Assertions.assertThrows(IOException.class, () -> logger.LogHostStream("logText"));事实上你应该调用Assertions.assertThrows(IOException.class, () -> logger.LogHostStream("logText")); to test your own method.测试你自己的方法。

The reason you can't get the exception is that () -> new BufferedWriter(bw));您无法获得异常的原因是() -> new BufferedWriter(bw)); will never throw any exception.永远不会抛出任何异常。 The place where exception is thrown is FileWriter fWriter = new FileWriter(logFileName, true);抛出异常的地方是FileWriter fWriter = new FileWriter(logFileName, true);

If you want to test your method to checkout whether it throws the excpeted exception, you should remove your try-catch block like this:如果你想测试你的方法来检查它是否抛出异常,你应该像这样删除你的 try-catch 块:

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

Because once you catch your exception, you can't check the exception with Assertions.assertThrows因为一旦捕获到异常,就无法使用Assertions.assertThrows检查异常

After that you should change the value of /config/log/host_logs in ocomw_config.xml to a invalid path value.之后,您应该将 ocomw_config.xml 中/config/log/host_logs ocomw_config.xml值更改为无效路径值。 Then call Assertions.assertThrows(IOException.class, () -> logger.LogHostStream("someLogText"));然后调用Assertions.assertThrows(IOException.class, () -> logger.LogHostStream("someLogText")); , and you will see the excepted exception. ,您将看到 excepted 异常。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM