1
I would 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 launched (simulating the release 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 launched.
Example of Try-with-Resources method to be tested:
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 above code, I would like to test a Case where Filewriter launches an Exception when building, and another case where the call to write(str)
launch an Exception, and even more a case where no Exception is launched.
- Would be a good idea "mock" Filewriter? How could this be done? How can I launch an Exception when building it to test this case?
- What about "mock" the Bufferedwriter to make the method
write(str)
launch an Exception?
In the tests I want to check whether an Exception has been launched (forcing it to be launched) and whether the method mostrarErroNaGUI(e)
received this Exception.
I also want to test the case where no Exception is launched by checking whether the method mostrarErroNaGUI(e)
nay was called.
The general idea is to simulate in Tests all Exceptions that can be launched in a Try-with-Resources, but how can I force on the Tests that these Exceptions are released to then make assertions that check whether the program handled them as expected?
So the intention is to have Tests that ensure that the code snippet will handle as expected regardless of the Exception occurring within it.
Your answer may modify this code to make it more testable, no problem, but can not delete the Try-with-Resources why simulating Exceptions inside it to make assertions after is the focus of this question.
Obs.: I’m using Junit5 and Mockito in my tests.
What do you want to test? It’s still just a chunk of code that for the test is a blackbox.
– Jefferson Quesado
@Jeffersonquesado I edited to try to clarify, see if I was able to express my question well enough now :)
– Douglas