【问题标题】:JMock with(instanceOf(Integer.class)) does not compile in Java 8JMock with(instanceOf(Integer.class)) 在 Java 8 中无法编译
【发布时间】:2015-05-06 21:20:20
【问题描述】:

升级到 Java 8 后。我现在遇到以下类型的编译错误:

The method with(Matcher<Object>) is ambiguous for the type new Expectations(){}

是这个方法调用引起的:

import org.jmock.Expectations;

public class Ambiguous {
    public static void main(String[] args) {
        Expectations expectations = new Expectations();
        expectations.with(org.hamcrest.Matchers.instanceOf(Integer.class));
    }
}

似乎从 instanceOf() 返回的 with 与 with() 的预期模棱两可,反之亦然。有没有办法解决这个问题?

【问题讨论】:

  • 确切的 JDK 版本? JMock 版本?一个完整的源代码示例会很有帮助。
  • 或许你可以给instanceof添加类型:expectations.with(org.hamcrest.Matchers.&lt;Integer&gt;instanceOf(Integer.class))

标签: generics migration java-8 hamcrest jmock


【解决方案1】:

有一些简单的方法可以帮助编译器。

将匹配器分配给局部变量:

public static void main(String[] args) {
    Expectations expectations = new Expectations();
    Matcher<Integer> instanceOf = Matchers.instanceOf(Integer.class);
    expectations.with(instanceOf);
}

您可以使用类型见证指定类型参数,如下所示:

public static void main(String[] args) {
    Expectations expectations = new Expectations();
    expectations.with(Matchers.<Integer>instanceOf(Integer.class));
}

将 instanceOf 包装在您自己的类型安全方法中:

public static void main(String[] args) {
    Expectations expectations = new Expectations();
    expectations.with(instanceOf(Integer.class));
}

public static <T> Matcher<T> instanceOf(Class<T> type) {
    return Matchers.instanceOf(type);
}

我更喜欢最后一种解决方案,因为它可以重复使用,并且测试仍然易于阅读。

【讨论】:

    猜你喜欢
    • 2014-12-24
    • 2017-04-09
    • 2012-07-06
    • 1970-01-01
    • 2021-06-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-19
    相关资源
    最近更新 更多