Unit Testing - How to test a try-with-resources?

1

I'd like to know the best way - or the standard way - to test a try-with-resources ; with Test Cases for each of the Exceptions that can be released (simulating the launch of each of these Exceptions to see how the tested code will behave), and with a Test Case for when everything goes well and no Exception is thrown.

Example method with try-with-resources to test:

public static void escreverNoFinalDoArquivo(String str, File arquivo) {
    try (BufferedWriter writer = new BufferedWriter(new FileWriter(arquivo, true))) {
        writer.write(str);
    } catch (NullPointerException | IOException e) {
        mostrarErroNaGUI(e);
    }
}

In the code above, I would like to test a Case where FileWriter throws an Exception when it is built, and another case where the call to write(str) throws an Exception, and yet another case where no Exception is thrown. >

  • Would it be a good idea to "mockar" FileWriter? How could this be done? How can I throw an Exception when constructing it to test this case?
  • What about "mock" BufferedWriter to make method write(str) throw an Exception?

In testing I want to check if an Exception has been thrown (forcing it to be thrown) and if the mostrarErroNaGUI(e) method has received this Exception. I also want to test the case where no Exception is thrown by verifying that the method mostrarErroNaGUI(e) was not called.

The general idea is to simulate all Exceptions that can be thrown on a try-with-resources , but how can I force the Exceptions to be thrown on then make assertions that verify that the program dealt with them as expected?

So, the intent is to have tests that ensure that the code snippet will handle as expected regardless of the Exception occurring within it.

Your response may modify this code to make it more testable, no problem, but you can not eliminate try-with-resources because simulating Exceptions inside it to make assertions is the focus of this question .

    
asked by anonymous 17.03.2018 / 03:16

0 answers