我寫jUnits並卡住了與Lambda表達式。嘲諷匿名函數
有沒有一種方法來模擬匿名函數?
return retryTemplate.execute(retryContext -> {
return mockedResponse;
});
在上面的代碼中,我試圖模擬retryTemplate
。 retryTemplate
是類型 - org.springframework.retry.support.RetryTemplate
我寫jUnits並卡住了與Lambda表達式。嘲諷匿名函數
有沒有一種方法來模擬匿名函數?
return retryTemplate.execute(retryContext -> {
return mockedResponse;
});
在上面的代碼中,我試圖模擬retryTemplate
。 retryTemplate
是類型 - org.springframework.retry.support.RetryTemplate
假設retryTemplate是在一些豆「爲myBean」的依賴關係,我會使用依賴注入嘲笑使用所述的Mockito方法retryTemplate.execute並將其配置爲接受任何參數:
RetryTemplate mockRetryTemplate = Mockito.mock(RetryTemplate.class);
Mockito.when(mockRetryTemplate.execute(Matchers.any(RetryCallback.class))).thenReturn(mockedResponse);
myBean.setRetryTemplate(mockRetryTemplate);
如果我只是試圖嘲諷一個方法的參數碰巧是一個lambda的參數,我可能會創建一個新的lambda表達式存根,而不是試圖嘲笑它。
對我來說@encrest的解決方案沒有奏效。
RetryTemplate mockRetryTemplate = Mockito.mock(RetryTemplate.class);
Mockito.when(mockRetryTemplate.execute(Matchers.any(RetryCallback.class))).thenReturn(mockedResponse);
我得到這個錯誤:
org.mockito.exceptions.misusing.InvalidUseOfMatchersException:
Invalid use of argument matchers!
3 matchers expected, 1 recorded:
-> at test1(ServiceTest.java:41)
This exception may occur if matchers are combined with raw values:
//incorrect:
someMethod(anyObject(), "raw String");
When using matchers, all arguments have to be provided by matchers.
For example:
//correct:
someMethod(anyObject(), eq("String by matcher"));
For more info see javadoc for Matchers class.
at org.springframework.retry.support.RetryTemplate.execute(RetryTemplate.java:164)
這個錯誤似乎有點愚蠢,因爲.execute()
應該只有1個參數(因此1匹配)工作。另請參閱non-sensical。
當尋找到RetryTemplate
來源,有4種.execute()
方法。一個有三個參數。所以我想這是與匹配器不能夠存根正確的方法。
最終的解決方案:
RetryTemplate mockRetryTemplate = Mockito.mock(RetryTemplate.class);
Mockito.when(mockRetryTemplate.execute(Matchers.any(RetryCallback.class), Matchers.any(RecoveryCallback.class), Matchers.any(RetryState.class))).thenReturn(mockedResponse);
我可以將其添加到原題:爲什麼不是匹配器能夠解決的一個參數的方法?
執行方法不適用於參數(Object)。它需要不同的參數集。 – user1879835
@ user1879835嘗試更換Matchers.any()與Matchers.any(RetryCallback.class) – encrest