欢迎您访问 最编程 本站为您分享编程语言代码,编程技术文章!
您现在的位置是: 首页

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

最编程 2024-04-21 16:57:59
...

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


大功告成!

推荐阅读