10

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.

user998692
  • 5,172
  • 7
  • 40
  • 63
  • 2
    Why do you think there is any difference to non-`default` methods? Did you find anything in the net saying you should not test `default` methods? How about `static` methods? – Holger Sep 16 '14 at 10:17
  • 1
    don’t philosophize about “roles” on a technical topic. The basic idea of unit testing is, if you have a piece of code of a certain complexity, write test code for it. Point. That’s why it is called “unit testing” and not “concrete (non-`interface`) classes testing”. Everything beyond that is “primarily opinion based” and a reason to close the question. – Holger Sep 16 '14 at 10:50
  • @Holger You can write all this as an answer for 6k people who viewed the question. Actually, the link in the answer below was useful for me. And your "closed" is opinion-based. – user9999 Jul 06 '21 at 15:18

1 Answers1

11

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.

Community
  • 1
  • 1
gontard
  • 28,720
  • 11
  • 94
  • 117
  • 2
    @user998692 the logic is exactly the same. Create a mock implementation, implement the required methods minimally and test the default ones. The CUT should not be mocked with a framework. – Boris the Spider Sep 16 '14 at 09:59
  • 1
    "It is basically a contract and it did not contain implementations at all." This is no more true since there is default methods. And you don't need a testing framework for writing a mock implementation – gontard Sep 16 '14 at 10:00