use*_*692 9 junit unit-testing java-8 default-method
我对Java 8中引入的接口中的默认方法实现感到有些困惑.我想知道是否应该专门为接口及其实现的方法编写JUnit测试.我试着谷歌,但我找不到一些指导方针.请指教.
gon*_*ard 10
它取决于方法的复杂性.如果代码是微不足道的,那就不是必需的,例如:
public interface MyInterface {
ObjectProperty<String> ageProperty();
default String getAge() {
return ageProperty().getValue();
}
}
Run Code Online (Sandbox Code Playgroud)
如果代码更复杂,那么您应该编写单元测试.例如,此默认方法来自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);
};
}
...
}
Run Code Online (Sandbox Code Playgroud)
怎么测试呢?
从接口测试默认方法与测试抽象类相同.
| 归档时间: |
|
| 查看次数: |
4700 次 |
| 最近记录: |