Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should we do unit testing for default methods in interfaces (Java 8)? [closed]

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.

like image 731
user998692 Avatar asked Sep 16 '14 09:09

user998692


1 Answers

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.

like image 69
gontard Avatar answered Sep 27 '22 20:09

gontard