JMock with(instanceOf(Integer.class)) does not compile in Java 8

一曲冷凌霜 提交于 2019-12-08 05:40:30

问题


After upgrading to Java 8. I now have compile errors of the following kind:

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

It is caused by this method call:

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

It seems like with is returned from instanceOf() is ambiguous from what with() expects, or vice versa. Is there a way to fix this?


回答1:


There is some easy ways to help the compiler.

assign the matcher to a local variable:

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

you can specify the type parameter with a type witness as follows:

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

wrap the instanceOf in your own type safe method:

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

I prefer the last solution since it is reusable and the test remains easy to read.



来源:https://stackoverflow.com/questions/30087751/jmock-withinstanceofinteger-class-does-not-compile-in-java-8

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!