10

我对 Java 8 中引入的接口中的默认方法实现感到有些困惑。我想知道我们是否应该专门为接口及其实现的方法编写 JUnit 测试。我试图用谷歌搜索它,但我找不到一些指导方针。请指教。

4

1 回答 1

11

它取决于方法的复杂性。如果代码很简单,则实际上没有必要,例如:

public interface MyInterface {
    ObjectProperty<String> ageProperty();
    default String getAge() {
        return ageProperty().getValue();
    }
}

如果代码更复杂,那么你应该编写一个单元测试。例如,这个默认方法来自Comparator

public interface Comparator<T> {
    ...
    default Comparator<T> thenComparing(Comparator<? super T> other) {
        Objects.requireNonNull(other);
        return (Comparator<T> & Serializable) (c1, c2) -> {
            int res = compare(c1, c2);
            return (res != 0) ? res : other.compare(c1, c2);
        };
    }
    ...
}

如何测试它?

从接口测试默认方法与测试抽象类相同。

这已经得到了回答。

于 2014-09-16T09:51:56.597 回答