【问题标题】:Using mockito; is it possible to mock a method that takes a lambda as a parameter and assert variables captured by the lambda?使用模拟;是否可以模拟一个将 lambda 作为参数并断言 lambda 捕获的变量的方法?
【发布时间】:2016-05-18 11:56:59
【问题描述】:

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

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 本身捕获的变量并断言它们是正确的值,如果它们是我正在寻找的值,则返回我的模拟响应。

【问题讨论】:

  • 使用Mock 对象应该是可行的。 Here 是关于这个主题的教程。
  • 这不是一个简单的断言,即您的模拟助手获得了某个方法调用(与 lambda 无关)吗?
  • @zapl no 我不这么认为,因为不会调用mockHelper.doSomething,因为delegate 也会被嘲笑。我会让问题更清楚
  • 您想验证对helper.doSomething 的调用,但无法验证helper 上的任何内容...这是矛盾的。
  • 可能是的;我想我希望我能以某种“神奇的方式”告诉 mockito 执行 suppiler 然后模拟将正常工作。

标签: java lambda mockito


【解决方案1】:

假设您的类 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();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-12-31
    • 1970-01-01
    • 2017-04-19
    • 2018-04-04
    • 2019-05-30
    • 1970-01-01
    • 2014-05-05
    • 2013-11-29
    相关资源
    最近更新 更多