Reputation: 11035
Android app, Having a function calling another function, that function may throw
static string SOME_DEFINE_1 = "some_define_1";
......
void myFunc() {
try {
HashMap<String, String> data = new HashMap<>();
data.put("key_1", SOME_DEFINE_1);
otherObject.func(data);
} catch (Throwable ex){
Log.e(TAG, "+++ exception from otherObject.func(), "+ ex.toString());
// do something
anotherFunc();
}
}
How to test the catch block is called when unit testing the myFunc?
Upvotes: 1
Views: 1976
Reputation: 9442
It isn't clear in your example where otherObject
comes from, but in general, to test the exception handling blocks you need code that will throw the exception. In this example, one way may be to mock the otherObject
and then use thenThrow
to cause it to throw an exception when the func(data)
method is called. You could use a spy
of the class you are testing and stub the anotherFunc method so you can replace it with something else and then verify if it was invoked for the conditions you expect to throw the exception.
These articles show the general approach:
So in a pseudo-code example:
// arrange
myClassUnderTest = spy(TheClassUnderTest);
otherObject = mock(OtherObject);
doNothing().when(myClassUnderTest).anotherFunc();
doThrow(new RuntimeException("simulated exception")).when(otherObject).func(any());
// act
myClassUnderTest.myFunc();
// assert
verify(myClassUnderTest , times(1)).anotherFunc();
Upvotes: 1