简体   繁体   English

测试方法还是try-catch?

[英]Test method or try-catch?

I was hoping that someone could tell me the best practice for the scenario I am running into with testing my code via junit4.我希望有人能告诉我通过junit4测试我的代码时遇到的场景的最佳实践。

My pseudocode is as follows:我的伪代码如下:

public class TestClass {

    private String readFromFile(String filePath) {
          use BufferedReader, get content file input
          append BufferedReader to StringBuffer
          return string
    }

    @Test
    public void testMethodOne() {
          String s = readFromFile(C:\fileOne);
          doStuff(s);
    }
}

The issue that I am having is that BufferedReader can throw an IOException.我遇到的问题是 BufferedReader 可以抛出 IOException。 If the readFromFile() method is not a method in the test I am classing (I only need it for these test scenarios), do I annotate it with @Test (expected = IOException.class) anyway, or should I use a try-catch block?如果 readFromFile() 方法不是我正在分类的测试中的方法(我只在这些测试场景中需要它),我是否应该使用@Test (expected = IOException.class)来注释它,还是应该使用 try-catch 块?

Thank you very much!非常感谢!

If it throws an exception and you're not expecting it to, then it's an exceptional situation.如果它抛出异常并且您不期望它,那么这是一个异常情况。 If the file cannot be read and the test cannot be performed, it's an error, it's not something related to the tests themselves.如果无法读取文件并且无法执行测试,则这是一个错误,与测试本身无关。

Add throws to the readFromFile method and to the test methods using it.throws添加到readFromFile方法和使用它的测试方法。

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

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