我们是否应该对接口中的默认方法进行单元测试(Java 8)? [英] Should we do unit testing for default methods in interfaces (Java 8)?
问题描述
我对Java 8中引入的接口中的默认方法实现感到有点困惑。我想知道是否应该专门为接口及其实现的方法编写JUnit测试。我试图谷歌它,但我找不到一些指导方针。请指教。
I feel a bit confused about the default methods implementations in interfaces introduced in Java 8. I was wondering if we should write JUnit tests specifically for an interface and its implemented methods. I tried to google it, but I couldn't find some guidelines. Please advise.
推荐答案
这取决于方法的复杂程度。如果代码很简单,则没有必要,例如:
Its depends on the method complexity. It is not really necessary if the code is trivial, for example:
public interface MyInterface {
ObjectProperty<String> ageProperty();
default String getAge() {
return ageProperty().getValue();
}
}
如果代码更复杂,那么你应该写单元测试。例如,此默认方法来自 Comparator
:
If the code is more complex, then you should write a unit test. For example, this default method from 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);
};
}
...
}
如何测试它?
从接口测试默认方法与测试抽象类相同。
Testing a default method from an interface is the same as testing an abstract class.
这篇关于我们是否应该对接口中的默认方法进行单元测试(Java 8)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!