The name implementation method for obtaining test classes and methods in JUnit _java

Source: Internet
Author: User

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!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.