简体   繁体   中英

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.

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. 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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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