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();
}
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With