使用模拟;是否可以模拟一个将 lambda 作为参数并断言由 lambda 捕获的变量的方法?

Gav*_*360 6 java lambda mockito

我有一个看起来像这样的方法:

public Response methodA(ParamObject po, Supplier<Response> supplier)
Run Code Online (Sandbox Code Playgroud)

在Supplier包含另一个类的方法的调用。

我试图将一些代码包装Supplier在一组更复杂的逻辑中,类似于策略模式,它确实使代码更易于遵循。

它看起来像:

public Controller {    
   private Helper helper;
   private Delegate delegate;

   public void doSomething() {
     ParamObject po = ....
     delegate.methodA(po, () -> {
         helper.doSomethingElse(v1, v2);
     }
   }

}
Run Code Online (Sandbox Code Playgroud)

在我的测试中,Controller我已经模拟了Helper和Delegate,我希望验证helper.doSomething使用正确的参数值调用它,然后返回模拟响应。

鉴于这delegate是一个模拟,Supplier从未真正执行过,因此无法模拟helper或验证对调用的验证。

是否有可能做到这一点?感觉就像我应该能够告诉 mockito 捕获 lambda,或者 lambda 本身捕获的变量,并断言它们是正确的值,如果它们是我正在寻找的值,则返回我的模拟响应。

Nic*_*tto 4

假设你的 Helper 类看起来像这样:

public class Helper {
    public Response doSomethingElse(String v1, String v2) {
        // rest of the method here
    }
}
Run Code Online (Sandbox Code Playgroud)

那么可以这样做:

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();
Run Code Online (Sandbox Code Playgroud)