【问题标题】:How to JUnit for method which is static and returns void如何为静态并返回 void 的方法进行 JUnit
【发布时间】:2021-03-16 13:50:27
【问题描述】:

如何为以下方法编写 JUnit?

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

我的代码:

@Test
public void testInvokeAuditService() {
    PowerMockito.doNothing().when(WidgetHelper.class);
    WidgetHelper.invokeAuditService(Matchers.anyObject(), Matchers.anyObject(), Matchers.anyObject(), 
            Matchers.anyObject(), Matchers.anyObject(), Matchers.anyObject());
}

我收到编译器错误: WidgetHelper类型中的invokeAuditService(HttpServletRequest, Date, String, String, JSONObject, String)方法不适用于参数(Object, Object, Object, Object, Object, Object)

更新代码:

@Test
    public void testInvokeAuditService() {
        
        PowerMockito.doNothing().when(WidgetHelper.class);
        WidgetHelper.invokeAuditService(servletRequest, date, "abc", "xyz",json, 
                "123");
        
        verifyStatic(WidgetHelper.class, Mockito.times(1));
        WidgetHelper.invokeAuditService(servletRequest, date, "abc", "xyz",json, 
                "123");
    }

这表示:verifystatic 之后的行“实际上与此模拟的交互为零”。

【问题讨论】:

    标签: java junit mockito powermock powermockito


    【解决方案1】:

    您在invokeAuditService 方法参数中将所有值作为Object 传递。所以你得到了这个编译器错误。

    例如,你应该传递serviceCallTime, response, activityKey, detailsReplaceVal, pmAccountId的值

    如果您没有所有参数的值,则将值作为null 值发送,但null 值应在invokeAuditService 方法中处理以避免NullpointerException

    如下修改代码

    @Test
    public void testInvokeAuditService() {
        PowerMockito.doNothing().when(WidgetHelper.class);
        WidgetHelper.invokeAuditService(null, null, null, null, null, null);    
    }
    

    现在您的编译器错误将得到解决,也许您将在运行时遇到NullpointerException

    【讨论】:

    • 我不能传递空值。我可以传递什么作为实际模拟参数的参数?
    • 你不应该传递null,你应该在需要的参数中传递实际值。
    【解决方案2】:

    这行得通:

    @Test
        public void testInvokeAuditServiceWithSuccessFlagAndResponse() {
            
            PowerMockito.doNothing().when(WidgetHelper.class);
            WidgetHelper.invokeAuditService(servletRequest, date, "abc", json, 
                    "123", "Y");
            
            verifyStatic(WidgetHelper.class, Mockito.times(1));
        }
    

    我实际上是在要求 Mockito 在交互发生之前验证交互。

    【讨论】:

      猜你喜欢
      • 2014-01-05
      • 2012-03-24
      • 1970-01-01
      • 1970-01-01
      • 2015-10-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多