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

时间:2021-08-22 22:47:36

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

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

?
1
2
3
4
5
6
7
8
9
10
11
12
13
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稍作修改如下:

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


在测试用例中的用法是:

?
1
2
3
4
5
6
7
8
9
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());
 }
}


大功告成!