【问题标题】:mockito, how to coverage test the catch blockmockito,如何覆盖测试 catch 块
【发布时间】:2021-08-16 23:59:34
【问题描述】:

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块被调用?

【问题讨论】:

    标签: mockito test-coverage android-junit


    【解决方案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();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-09
      • 1970-01-01
      相关资源
      最近更新 更多