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


在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());
 }
}


大功告成!


« 
» 
快速导航

Copyright © 2016 phpStudy | 豫ICP备2021030365号-3