0

Android应用程序,有一个函数调用另一个函数,该函数可能会抛出

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();
        }
    }

单元测试myFunc时如何测试catch块被调用?

4

1 回答 1

1

在您的示例中不清楚otherObject来自哪里,但通常,要测试异常处理块,您需要将引发异常的代码。在此示例中,一种方法可能是模拟otherObject并使用它在调用该方法thenThrow时引发异常。func(data)您可以使用spy您正在测试的类中的一个并存根 anotherFunc 方法,以便您可以将其替换为其他内容,然后验证它是否已针对您期望引发异常的条件调用。

这些文章显示了一般方法:

所以在一个伪代码示例中:

// 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();
于 2021-05-28T21:20:33.930 回答