In JUnit tests, it is sometimes necessary to obtain the name of the class or method to which it belongs, so as to make it easier to log something.
The TestName class is provided in JUnit to do this, in 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
fNa Me;
}
Although TestName only provides the name of the method, it is easy to add the name of the class, just modify the testname slightly as follows:
protected void starting (Description d) {
fName = d.getclassname () + "." + D.getmethodname ();
}
The usage in test cases 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!