使用模仿是否可以模拟将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?

查看:84
本文介绍了使用模仿是否可以模拟将lambda作为参数并声明由lambda捕获的变量的方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a method that looks that looks something like:

public Response methodA(ParamObject po, Supplier<Response> supplier)

Supplier包含对另一个类上的方法的调用.

the Supplier contains a call to a method on another class.

我正在尝试将某些代码包装在Supplier中,使用更复杂的逻辑集,类似于Strategy模式,它确实使代码更易于遵循.

I am attempting to wrap some code in the Supplier in a more complex set of logic, something akin to a Strategy pattern, it does make the code easier to follow.

它看起来像:

public Controller {    
   private Helper helper;
   private Delegate delegate;

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

}

在对Controller的测试中,我同时模拟了HelperDelegate,我希望验证是否使用正确的参数值调用了helper.doSomething,然后返回模拟的响应.

In my test for Controller I have mocked both Helper and Delegate, I wish to validate that helper.doSomething is called with the correct parameter values, and then return a mocked response.

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

Given that delegate is a mock, the Supplier is never actually executed, so no verification of the calls to helper can be mocked or verified.

是否可以这样做?感觉好像我应该能够告诉mockito捕获lambda,或者lambda本身捕获的变量并断言它们是正确的值(如果它们是我正在寻找的值)将返回我的模拟响应.

Is it possible to do this? It feels like I should be able to tell mockito to capture the lambda, and or the variables the lambda itself captured and assert they are the right values return my mock response if they are the values I was looking for.

推荐答案

假设您的类帮助器如下所示:

Assuming that your class Helper looks like this:

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();

这篇关于使用模仿是否可以模拟将lambda作为参数并声明由lambda捕获的变量的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆