-3

I am trying to write a JUnit for the below code but I am not getting any idea how to cover the code which is written in the catch block statement. Please can anyone write a sample JUnit for the below code?

Here I don't want to cover any exception since this block never throws any, but want to cover the lines of code written in the catch block using Mockito. Basically, the catch block is unreachable in this case.

public void someMethod(Activity activity) {
    try {
        Log.d("TAG", "Print: " + activity);
    } catch (Throwable e) {
        e.printStackTrace();
    }
}
Lukasz Blasiak
  • 642
  • 2
  • 10
  • 16
  • Welcome to Stack Overflow. Please take the [tour] to learn how Stack Overflow works and read [ask] on how to improve the quality of your question. Then [edit] your question to include the full source code you have as a [mcve], which can be compiled and tested by others. Please show your attempts you have tried and the problems/error messages you get from your attempts. – Progman May 02 '21 at 10:05
  • 2
    What value of `activity` do you think could cause the call to `Log.d` to fail? – jonrsharpe May 02 '21 at 10:16
  • If the catch block is truly unreachable, why is it there at all, and why do you want to cover it, given that it's never gonna be executed? Furthermore, how do you expect to be able to cover it, if it can't ever run, on account of it being unreachable? – JustAnotherDeveloper May 02 '21 at 10:27

1 Answers1

0

Without Mockito:

Create a new Activity class that extends Activity. On its toString() code, throw an exception.

class ExceptionActivity extends Activity {
    @Override
    public String toString() {
        throw new RuntimeException("mock exception");
    }
}

When you try to print an activity object, you'll get an exception.

With Mockito:

public void someMethod(Activity activity) {
    try {
        someService.doJob(activity);
    } catch (Throwable e) { 
        e.printStackTrace(); 
    }
}

You can simulate an exception this way:

when(someService.doJob(any())).thenThrow(new RuntimeException("mock exception"));