问题
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.
回答1:
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();
}
}
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);
};
}
...
}
How to test it?
Testing a default method from an interface is the same as testing an abstract class.
This has already been answered.
来源:https://stackoverflow.com/questions/25865616/should-we-do-unit-testing-for-default-methods-in-interfaces-java-8