首页 > 解决方案 > 如何知道当前触发了哪个测试

问题描述

我有下一个代码

class Test extend Parent{

 @Test
  public void testMethod(){
  };
}

class Parent {
  'here I need to have some check which test is running now'
}

至于在Test类之前初始化Parent类,如何知道现在正在运行哪个jUnit测试或者如果有多个子类是哪个子类?

标签: javajunit

解决方案


您可以通过以下方式获取启动父类创建的后代类的名称:

// in the constructor of the parent System.out.println(Thread.currentThread().getStackTrace()[2].getClassName());

在多继承级别的情况下,您可以编写一些额外的自定义逻辑并遍历当前堆栈跟踪。

免责声明:您将要做的事情看起来并不好。使用内置功能,如@Before@BeforeClass或进行一些重构可能是更好的解决方案。


推荐阅读