簡體   English   中英

使用mockito; 是否有可能模擬一個方法,該方法將lambda作為參數並斷言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測試中,我已經模擬了HelperDelegate ,我希望驗證使用正確的參數值調用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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM