Gio
Gio

Reputation: 359

How can I write a test case for an interface?

I need to get 100% code coverage for an interface class, how can I write a junit test case to test an interface.

public interface RetrieveOperation {
  public RetrieveClassOfServiceProfileResponse
      retrieve(String login, RetrieveClassOfServiceProfileRequest request)
      throws Exception;
}

Upvotes: 2

Views: 5332

Answers (2)

dimo414
dimo414

Reputation: 48864

As you can see, there's nothing in that interface to test. You cannot have, and don't need, 100% coverage of a pure interface.

Depending on what you're trying to do, you can just write unit tests like you normally would for the individual implementations. To enforce an interface's behavior generally you can write a helper class / method(s) that checks the invariants of an arbitrary implementation, then have a test in the implementation's unit tests that calls that helper.

E.g.

public class RetrieveOperationVerifier {
  public static void assertValid(RetrieveOperation impl) {
    // assert impl behaves as expected
  }
}

public class ConcreteRetrieveOperationImplTest {
  // other tests

  public void invariantTest() {
    RetrieveOperationVerifier.assertValid(new ConcreteRetrieveOperationImpl());
  }
}

Upvotes: 1

Philipp
Philipp

Reputation: 69683

An interface doesn't do anything on its own, so there is no reason and no way to test it. It's only meaningful to test a class which implements an interface.

An exception to this are static methods (which can be easily tested because you don't need an instance) and the new default methods in Java 8. You don't have one like that in this example, but if you would have one, you would test it by creating a minimal class which implements the interface by implementing all non-default methods with a no-op and then use that to test the default methods.

Upvotes: 3

Related Questions