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

一世执手 提交于 2019-12-05 20:28:39

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!