在执行单元测试期间检查是否连接了调试器 [英] Check if a debugger is attached during the execution of a unit test

查看:79
本文介绍了在执行单元测试期间检查是否连接了调试器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有一种方法可以检查JUnit代码是否将调试器附加到当前测试执行中?
在.NET/C#中,我知道可以使用Debugger.IsAttached.

Is there a way to check in JUnit code if the debugger is attached to the current test execution?
In .NET/C# i know this is possible with Debugger.IsAttached.

用例是在连接调试器时更改或完全禁用测试超时,因为如果您只有大约15秒(定义的超时)用于调试测试,这将很烦人.

The use case would be to change or completly disable test timeouts when the debugger is attached because this is pretty annoying if you only have about 15 seconds (the defined timeout) for debugging a test.

推荐答案

这不是100%故障安全的方法,但是您可以检查

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;
}

但是,如果其他人将其命名为jdwp,或者该协议被用于其他内容,则可能返回假阳性.另外,该命令将来可能会更改,这使得此功能很难失效.这种方法当然不是特定于JUnit的,但是由于JUnit在JVM中没有任何特权,因此这是很自然的.

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.

这篇关于在执行单元测试期间检查是否连接了调试器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆