Gets the name implementation method of the test class and method in JUnit

  • 2020-04-01 03:55:11
  • OfStack

In JUnit's tests, sometimes you need to get the name of the Class or Method you belong to to facilitate logging or something.

In JUnit provides (link: https://github.com/junit-team/junit/blob/master/src/main/java/org/junit/rules/TestName.java) class to do this, in the org. JUnit. Rules:


public class TestName extends TestWatcher {
 private String fName;
 @Override
 protected void starting(Description d) {
  fName = d.getMethodName();
 }
 
 public String getMethodName() {
  return fName;
 }
}


Although TestName only provides the name of the method, it is easy to add the name of the class by modifying TestName slightly as follows:


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


The usage in the test case is:


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


Done!


Related articles: