2

For eg.

try {
    // Some code
} 
catch (IOException e) {
    throw new CustomDefineException(e);
}

I want to write mockito coverage statement for the catch block. How can that be done? I'm new on mockito framework.

khelwood
  • 55,782
  • 14
  • 81
  • 108
Anmol Khanna
  • 95
  • 2
  • 9
  • 3
    To get coverage you have to set up a test case that causes an `IOException` to be thrown. The code you show does not throw an IOException though so it's impossible for the code in the catch block to run. – Joni Aug 24 '20 at 14:19
  • 1
    Ohh.. so you mean until or unless an exception is thrown or an explicit test case is written for the exception, it won't be covered? – Anmol Khanna Aug 24 '20 at 14:28
  • 1
    Yes, that's how it works – Joni Aug 24 '20 at 14:51

2 Answers2

0

So basically as per Joni, we can only test the catch block, when there is actually an exception that is occurring, till then it cannot be tested.

Anmol Khanna
  • 95
  • 2
  • 9
0

You can write the test cases that actually make the code to throw exception. The control would go to the Catch Block and your coverage would increase.

For the test case to pass you can write the test case that would expect to get exception like

@Test(expected = CustomDefineException.class)
public void shouldThrowCustomDefineExceptionWhenWrongParameterIsSupplied() {
    // Your Logic to create Exception
    }

on the top of the test Method.

Tushar Jajodia
  • 433
  • 5
  • 15