0

I would like to create a test case to test this catch block

I want to test this message "File does't exit, please put the file inside resources folder." and FileNotFoundException exception using testNG.

try { //something here 

} catch (FileNotFoundException ex) { 
    System.out.println("File does't exit, please put the file inside resources folder.");
    ex.printStackTrace(); 
}
OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
Jack
  • 11
  • You may find some good ideas on [this question](https://stackoverflow.com/q/3677271/1081110), especially harunurhan's answer. – Dawood ibn Kareem Sep 20 '22 at 00:27
  • thank you Dawood, how about the body of the test case I already did the same but no good results – Jack Sep 20 '22 at 00:39
  • All you need to do in the body of your test case is run the method that throws the exception. If you've set up the `@Test` annotation properly, with the right `expectedExceptions` and `expectedExceptionsMessageRegExp` values, you don't need any other assertions. – Dawood ibn Kareem Sep 20 '22 at 00:42
  • I did the same but still fail @Test(expectedExceptions = FileNotFoundException.class) public void testCatchBlockInTask() { //method that throws the exception } – Jack Sep 20 '22 at 00:50
  • Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking. – Community Sep 20 '22 at 02:32
  • 1
    Use `ex.getMessage()` and then use `testNG` `assertion` to verify. – Nandan A Sep 20 '22 at 05:43
  • @NandanA How will that test the System.out.println output? – OneCricketeer Sep 20 '22 at 05:50
  • @OneCricketeer I think the question is not clear. He wants to do something like this `Assert.assertEquals(e.getMessage(), "File doesn't..");` – Nandan A Sep 20 '22 at 05:52
  • @NandanA There's no `e` being returned to any unit test – OneCricketeer Sep 20 '22 at 05:59
  • @DawoodibnKareem Those suggestions will only work if the method under test actually throws, no? – OneCricketeer Sep 20 '22 at 06:01
  • Yes, @OneCricketeer, that's what Jack is trying to test. – Dawood ibn Kareem Sep 20 '22 at 20:35

2 Answers2

-2

Try this code, you will get the FileNotFoundException, the file 'test.txt' should not be available in the path:

    @Test
    public void fileSetup() {    
        try {
            File file = new File("C:\\Users\\test\\Desktop\\test.txt");
            Scanner sc = new Scanner(file);

            System.out.println(sc.next());
            sc.close();
        } catch (FileNotFoundException e) {
            System.out.println("In catch block");
            e.printStackTrace();
        }
    }     
AbiSaran
  • 2,538
  • 3
  • 9
  • 15
-2

Ideally, you don't use System output. You'd rather inject a logger and test against that.

But, it can still be done

// Store the original standard out before changing it.
private final PrintStream originalStdOut = System.out;
private ByteArrayOutputStream consoleContent = new ByteArrayOutputStream();
 
@BeforeMethod
public void beforeTest() {
    // Redirect all System.out to consoleContent.
    System.setOut(new PrintStream(this.consoleContent));
}

You may need to do something similar for System.err for ex.printStackTrace() output...

Then run your function in a standard test, and assert against the consoleContent contents.

@Test
public void testFileExistence() {    
    doSomething("missing-file.txt");  // call a method of your service code that prints an exception
    
    int n = this.consoleContent.available();
    byte[] bytes = new byte[n];
    this.consoleContent.read(bytes, 0, n);
    String s = new String(bytes, StandardCharsets.UTF_8);
    // TODO: split on line-breaks, and test printed content
}   

After each test, you'll need to reset the stream, and if you still want to print the data, then do that too

@AfterMethod
public void afterTest() {
    // Put back the standard out.
    System.setOut(this.originalStdOut);
 
    // Print what has been captured.
    System.out.println(this.consoleContent.toString());
    System.out.println(String.format("              ====>Captured Console length=%d",
            this.consoleContent.toString().length()));
 
    // Clear the consoleContent.
    this.consoleContent = new ByteArrayOutputStream();
}

Or, more ideally, you define your own RuntimeException / Exception subclasses, then use assertThrows methods, where you can properly verify exception object content, including the message body.

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245