[英]Detecting a call to a Java API method from source code
Suppose that I want to write a unit test for a method or class that makes sure that the source code of that method does not call a certain Java API method (in this case, Arrays.sort
). 假设我想为一个方法或类编写一个单元测试,以确保该方法或源代码不会调用某个Java API方法(在本例中为
Arrays.sort
)。 Is this even possible? 这有可能吗? The reason for which I want this is because I want to come up with automatic tests that detect if
Arrays.sort
has been called from anywhere inside a particular method of a particular class, in which case I want to be failing the relevant test. 我之所以想要这样做,是因为我想提出一种自动测试,以检测是否已从特定类的特定方法内的任何位置调用
Arrays.sort
,在这种情况下,我想使相关测试失败。 Unfortunately, a text-based approach is purely unsatisfactory, because it would also catch potential references to Arrays.sort from within source code comments, for instance. 不幸的是,基于文本的方法是完全不能令人满意的,因为例如,它还会从源代码注释中捕获对Arrays.sort的潜在引用。 Any help appreciated.
任何帮助表示赞赏。
You can do it by creating your interface for sorting and an implementation that uses Arrays.sort 您可以通过创建用于排序的接口以及使用Arrays.sort的实现来实现
public interface SortUtil {}
public class SortUtilImpl implements SortUtil {
public void sort(Collection c) {
Arrays.sort(c);
}
}
Now you must use the interface in your 'client' class for sorting. 现在,您必须使用“客户端”类中的接口进行排序。 For unit tests, replace the real implementation by a test mock one.
对于单元测试,将实际实现替换为模拟测试。 like:
喜欢:
public SortUtilMock implements SortUtil {
public void sort( Collection c) {
StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace();
//... here you check if the sort is called by a forbidden method
}
}
Best regards, Zied 最好的问候,Zied
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.