Skip to content

Instantly share code, notes, and snippets.

@johndstein
Last active January 2, 2021 18:06
Show Gist options
  • Save johndstein/c51ed4fa7906aae37f67fdb329675c23 to your computer and use it in GitHub Desktop.
Save johndstein/c51ed4fa7906aae37f67fdb329675c23 to your computer and use it in GitHub Desktop.
Salesforce APEX Stacktrace test if code is below given class.method
@isTest
private class StackTrace_Test {
public class MyException extends Exception {}
static testMethod void test() {
Test.StartTest();
someMethod();
Test.StopTest();
}
static void someMethod() {
System.debug('someMethod');
anotherMethod();
}
static void anotherMethod() {
System.debug('anotherMethod');
finalMethod();
}
static void finalMethod() {
System.debug('finalMethod');
System.debug(isClassMethod('Foo', 'bar'));
System.debug(isClassMethod('StackTrace_Test', 'bar'));
System.debug(isClassMethod('StackTrace_Test', 'test'));
System.debug(isClassMethod('StackTrace_Test', 'someMethod'));
System.debug(isClassMethod('StackTrace_Test', 'anotherMethod'));
System.debug(isClassMethod('StackTrace_Test', 'finalMethod'));
new FatCatClass().fatCatMethod();
}
// isClassMethod will return true if we are somewhere under the given
// className and methodName in the stack trace.
static boolean isClassMethod(String className, String methodName) {
// Must be DmlException. MyException won't work.
String[] lines = new DmlException().getStackTraceString().split('\\n');
for (String l : lines) {
// System.debug('Stack line: ' + l);
if (l.contains('.' + className + '.' + methodName)) {
return true;
}
}
return false;
}
public class FatCatClass {
void fatCatMethod() {
System.debug(isClassMethod('FatCatClass', 'fatCatMethod'));
System.debug(isClassMethod('StackTrace_Test', 'anotherMethod'));
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment