当前位置: 移动技术网 > IT编程>开发语言>Java > JUnit中获取测试类及方法的名称实现方法

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

2019年07月22日  | 移动技术网IT编程  | 我要评论

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


大功告成!

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网