Reputation: 52
I am new to jUnit. Can not figure out how to test handled exception.
public File inputProcessor(String filePath){
File file = null;
try {
file = new File(filePath);
Scanner input = new Scanner(file);
} catch (FileNotFoundException e) {
System.out.print("Check your input file path");
e.printStackTrace();
}
return file;
}
Now, want to test with a invalid file path to check whether exception is thrown and caught properly. I wrote this
@Test (expected = java.io.FileNotFoundException.class)
public void Input_CheckOnInvalidPath_ExceptionThrown() {
Driver driver = new Driver();
String filePath = "wrong path";
File file = driver.inputProcessor(filePath);
}
But as I have already caught my exception its not working. Test is failing . Any help will be great!! thnx
Upvotes: 0
Views: 498
Reputation: 326
You need to test your method's behavior, not its in implementation details.
If the correct behavior of your method is to return null
when the file does not exist, you just need
@Test
public void Input_CheckOnInvalidPath_ExceptionThrown() {
Driver driver = new Driver();
String filePath = "wrong path";
assertNull(driver.inputProcessor(filePath));
}
If the correct behavior of your method is to print a particular message to System.out
when the file does not exist, and you want to test that, then you can create a mock PrintStream
, use System.setOut(PrintStream)
to set it, call your method, and then test that the PrintStream
was invoked correctly. Mockito can help you do that -- maybe. I think you run the risk of testing the implementation detail that System.out.println()
vs many System.out.print()
is invoked. (You probably shouldn't be testing how e.printStackTrace()
is implemented.)
If the correct behavior is both, then you need both checks.
Upvotes: 3
Reputation: 26175
The exposed behavior you need from the method is the appearance of appropriate lines in System.out
and System.err
. In your test code, you can replace System.out and System.err with your own PrintStream
. See System.setOut and System.setErr.
Base each PrintStream on e.g. a StringWriter. That way, in your test code you can pick up the String representing what, if anything, the method wrote to each output stream, and do tests on it.
Upvotes: 1