JMock с (instanceOf(Integer.class)) не компилируется в Java 8

После обновления до 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() ожидает или наоборот. Есть ли способ это исправить?

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

Я предпочитаю последнее решение, так как оно многоразово, и тест остается легко читаемым.

Другие вопросы по тегам