【问题标题】:How to take the specifical class for lambda expression, e.g. subclass of the type in method parameters如何获取 lambda 表达式的特定类,例如方法参数中类型的子类
【发布时间】:2016-07-27 02:50:29
【问题描述】:

我正在尝试添加自定义的ArgumentMatcher(subclass of Matcher) 用于模拟测试,以下是代码:

when(mockedObject.mockedMethod(
   argThat((int id)-> id > 5 || id < 1 ? false : true)));

但我收到错误:

在接口 org.hamcrest.Matcher 中找到多个非覆盖抽象方法

我知道argThat被定义为:

public static <T> T argThat(Matcher<T> matcher)

我可以告诉编译器我想在 lambda 表达式中使用 ArgumentMatcher,而不是 Matcher 吗?

谢谢!

【问题讨论】:

    标签: lambda mockito


    【解决方案1】:

    不,你想要的是不可能的。 org.hamcrest.Matcher 不是功能接口。它有多种非抽象方法。例如以下任何一个:

    • org.hamcrest.SelfDescribing.describeTo(Description)
    • org.hamcrest.Matcher.matches(Object)

    编译器需要将 lambda 转换为功能接口的实现。但是ArgumentMatcher本身已经是一个类了。

    作为一种解决方法,您可以创建自己的argThat 版本,接收java.util.function.Predicate 并将其转换为Matcher 实现。但是,您将失去SelfDescribing 的支持,并且不得不忍受糟糕的故障描述。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-05
      • 1970-01-01
      • 1970-01-01
      • 2013-02-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多