您的位置:首页 > 其它

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

2015-06-10 09:43 786 查看

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


大功告成!

您可能感兴趣的文章:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息