简体   繁体   中英

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 ). 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. 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. Any help appreciated.

You can do it by creating your interface for sorting and an implementation that uses 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM