[英]How to JUnit for method which is static and returns void
如何為以下方法編寫 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());
}
I am getting compiler error: The method invokeAuditService(HttpServletRequest, Date, String, String, JSONObject, String) in the type WidgetHelper is not applicable for the arguments (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 之后的行“實際上與這個模擬的交互為零”。
您在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
這有效:
@Test
public void testInvokeAuditServiceWithSuccessFlagAndResponse() {
PowerMockito.doNothing().when(WidgetHelper.class);
WidgetHelper.invokeAuditService(servletRequest, date, "abc", json,
"123", "Y");
verifyStatic(WidgetHelper.class, Mockito.times(1));
}
我實際上是在要求 Mockito 在交互發生之前驗證交互。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.