首页 > 解决方案 > 使用 void 方法的 doNothing 方法时出现 UnfinishedStubbingException

问题描述

下面的代码导致 UnfinishedStubbingException

PowerMockito.doNothing().when(widgetHelper).invokeAuditService(Matchers.eq(servletRequest), Matchers.eq(date), anyString(), Matchers.eq("Member_Servicing_Email_Update"), Matchers.eq(jsonObject), anyString());

     verify(widgetHelper, times(1)).invokeAuditService(Matchers.eq(servletRequest), Matchers.eq(date), anyString(), Matchers.eq("Member_Servicing_Email_Update1"), Matchers.eq(jsonObject), anyString());


org.mockito.exceptions.misusing.UnfinishedStubbingException: 
Unfinished stubbing detected here:
    -> at ....

    E.g. thenReturn() may be missing.
    Examples of correct stubbing:
        when(mock.isOk()).thenReturn(true);
        when(mock.isOk()).thenThrow(exception);
        doThrow(exception).when(mock).someVoidMethod();
    Hints:
     1. missing thenReturn()
     2. you are trying to stub a final method, you naughty developer!

我在这里想念什么?下面是invokeAuditService的方法签名

public static void invokeAuditService(HttpServletRequest request, Date serviceCallTime, String response, 
            String activityKey, JSONObject detailsReplaceVal, String pmAccountId){
        AuditLogUtils.invokeAuditService(request, date, response, activityKey, json,  someString);
    }

我这样做了:

PowerMockito.mockStatic(WidgetHelper.class);
        PowerMockito.doNothing().when(WidgetHelper.class);
        WidgetHelper.invokeAuditService(Matchers.eq(servletRequest), Matchers.eq(date), anyString(), 
                Matchers.eq("Member_Servicing_Email_Update"), Matchers.eq(jsonObject), anyString());

verify(widgetHelper, times(1)).invokeAuditService(Matchers.eq(servletRequest), Matchers.eq(date), anyString(), 
                Matchers.eq("Member_Servicing_Email_Update123"), Matchers.eq(jsonObject), anyString());

Junit 运行没有任何错误,但它应该会失败,因为我已经通过并在Member_Servicing_Email_Update它的whenverifyMember_Servicing_Email_Update123

标签: javajunitmockitopowermockito

解决方案


该错误是由以下行引起的,该行是无效的语法: PowerMockito.doNothing().when(WidgetHelper.class);

当您创建一个模拟所有它的方法调用默认为doNothing. 所以你不需要明确声明它。

但是,如果要声明行为,则需要命名相关方法。给定行中缺少哪个。


推荐阅读