JUnit中获取测试类及方法的名称实现方法

内容摘要
在JUnit的测试中,有时候需要获得所属的类(Class)或者方法(Method)的名称,以方便记录日志什么的。
在JUnit中提供了TestName类来做到这一点,在org.junit.rules中:




public class T
文章正文

在JUnit的测试中,有时候需要获得所属的类(Class)或者方法(Method)的名称,以方便记录日志什么的。

在JUnit中提供了TestName类来做到这一点,在org.junit.rules中:

public class TestName extends TestWatcher {
 private String fName;
 @Override
 protected void starting(Description d) {
  fName = d.getMethodName();
 }
 /**
  * @return the name of the currently-running test method
  */
 public String getMethodName() {
  return fName;
 }
}


虽然TestName只提供了方法的名称,要加上类的名称很容易,只需对TestName稍作修改如下:

protected void starting(Description d) {
 fName = d.getClassName() + "." + d.getMethodName();
}


在测试用例中的用法是:

public class NameRuleTest {
 @Rule public TestName name = new TestName();
 @Test public void testA() {
  assertEquals("testA", name.getMethodName());
 }
 @Test public void testB() {
  assertEquals("testB", name.getMethodName());
 }
}


大功告成!


代码注释

作者:喵哥笔记

IDC笔记

学的不仅是技术,更是梦想!