Check if a debugger is attached during the execution of a unit test
Based on Rafael answer:
private static boolean isDebug() {
return ManagementFactory.getRuntimeMXBean().getInputArguments().stream().anyMatch(arg->arg.contains("jdwp=") && arg.contains("suspend=y"));
}
It is not a 100% fail-safe approach but you can check if the Java Debug Wire Protocol (JDWP) is active which is used by the debugger to connect to a JVM. This can be done by checking for input arguments to the JVM as for example in:
boolean isDebug() {
for(String arg : ManagementFactory.getRuntimeMXBean().getInputArguments()) {
if(arg.contains("jdwp=")) {
return true;
}
}
return false;
}
It might however return a false positive if anybody else named something jdwp
or if the protocol was used for something else. Also, the command might change in the future what makes this hardly fail-safe. This approach is of course not JUnit specific but as JUnit does not have any privileges within a JVM, this is only natural.