0

I need to write a test to verify that when an IOException is thrown by the private method_C, Method_B returns True. But

public final class A{

 public static Boolean Method_B(){

try{

 //call a private method C which throws IOException
    Method_C

}

catch(final IOException e) {
return Boolean.True
}


}

private static Method_C() throws IOException {
        return something;
    }

What I tried:

@Test
public void testSomeExceptionOccured() throws IOException {
     A Amock = mock(A.class);
     doThrow(IOException.class).when(Amock.Method_C(any(),any(),any(),any()));
     Boolean x = A.Method_B(some_inputs);
     Assert.assertEquals(Boolean.TRUE, x);
}

I am getting compilation errors : 1.Cannot mock a final class 2. Method_C has private access in A

Any suggestions on how this can be rectified?

raosa
  • 119
  • 1
  • 8
  • https://stackoverflow.com/a/14292888/2478398 And https://stackoverflow.com/a/7804428/2478398? – BeUndead Jul 09 '21 at 20:22
  • 2
    Test against the public interface, not the private implementation. What are the conditions which cause the exception to be thrown? Change the public method input and/or the (mocked) dependencies to cause the exception to be thrown. – Andrew S Jul 09 '21 at 20:30
  • @BeUndead is correct, and also this: https://stackoverflow.com/questions/21105403/mocking-static-methods-with-mockito – Michael Peacock Jul 14 '21 at 15:44

1 Answers1

-2

you are required to use finally in try catch

import java.io.*;
public class Test {
 public static Boolean Method_B() {
    try {
        System.out.println("Main working going..");
        File file = new File("./nofile.txt");
        FileInputStream fis = new FileInputStream(file);

    } catch (IOException e) {
        // Exceptiona handling
        System.out.println("No file found ");
    } catch (Exception e) {
        // Exceptiona handling
        System.out.println(e);
    } finally {
        return true;
    }
}
public static void main(String args[]) {
    if (Test.Method_B()) {
        System.out.println("Show true ans");
    } else {
        System.out.println("Sorry error occure");
    }

}
}