Last active
January 2, 2021 18:06
-
-
Save johndstein/c51ed4fa7906aae37f67fdb329675c23 to your computer and use it in GitHub Desktop.
Salesforce APEX Stacktrace test if code is below given class.method
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@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