在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()); } } |
大功告成!