[英]Mockito; Mock a method that calls a lambda, and verify another mock called by that lambda
[英]Using mockito; is it possible to mock a method that takes a lambda as a parameter and assert variables captured by the lambda?
我有一個看起來像這樣的方法:
public Response methodA(ParamObject po, Supplier<Response> supplier)
Supplier
包含對另一個類的方法的調用。
我試圖在一個更復雜的邏輯集中包含Supplier
中的一些代碼,類似於策略模式,它確實使代碼更容易遵循。
它看起來像:
public Controller {
private Helper helper;
private Delegate delegate;
public void doSomething() {
ParamObject po = ....
delegate.methodA(po, () -> {
helper.doSomethingElse(v1, v2);
}
}
}
在我對Controller
測試中,我已經模擬了Helper
和Delegate
,我希望驗證使用正確的參數值調用helper.doSomething
,然后返回模擬的響應。
鑒於delegate
是模擬, Supplier
從未實際執行,因此不能模擬或驗證對helper
程序的調用的驗證。
是否有可能做到這一點? 感覺我應該能夠告訴mockito捕獲lambda,以及lambda本身捕獲的變量,並斷言它們是正確的值,如果它們是我正在尋找的值,則返回我的模擬響應。
假設您的類Helper看起來像這樣:
public class Helper {
public Response doSomethingElse(String v1, String v2) {
// rest of the method here
}
}
然后就可以這樣做:
Helper helper = mock(Helper.class);
// a and b are the expected parameters
when(helper.doSomethingElse("a", "b")).thenReturn(new Response());
// a and c are not the expected parameters
when(helper.doSomethingElse("a", "c")).thenThrow(new AssertionError());
Delegate delegate = mock(Delegate.class);
// Whatever the parameters provided, simply execute the supplier to
// get the response to provide and to get an AssertionError if the
// parameters are not the expected ones
when(delegate.methodA(any(), any())).then(
new Answer<Response>() {
@Override
public Response answer(final InvocationOnMock invocationOnMock) throws Throwable {
return ((Supplier<Response>) invocationOnMock.getArguments()[1]).get();
}
}
);
Controller controller = new Controller();
controller.helper = helper;
controller.delegate = delegate;
controller.doSomething();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.