[英]How can I write a junit test case for default methods of interface with zero lines of code
[英]How can I write a test case for an interface?
我需要为接口类获得100%的代码覆盖率,如何编写junit测试用例来测试接口。
public interface RetrieveOperation {
public RetrieveClassOfServiceProfileResponse
retrieve(String login, RetrieveClassOfServiceProfileRequest request)
throws Exception;
}
一个接口本身没有做任何事情,所以没有理由也没办法测试它。 测试实现接口的类是唯一有意义的。
一个例外是static
方法(可以很容易地测试,因为你不需要实例)和Java 8中的新default
方法。在这个例子中你没有这样的方法,但如果你有一个,您可以通过创建一个实现接口的最小类来测试它,方法是使用no-op实现所有非默认方法,然后使用它来测试默认方法。
如您所见,该界面中没有任何内容可供测试。 您不能拥有,也不需要100%覆盖纯接口。
根据您要执行的操作,您可以像通常那样为单个实现编写单元测试。 为了强制执行接口的行为,通常可以编写一个帮助程序类/方法来检查任意实现的不变量,然后在实现的单元测试中进行测试,调用该帮助程序。
例如
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());
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.