UmAnusorn
UmAnusorn

Reputation: 11124

How to automate the method name in JUnit?

My code will auto get the className and method name. This will helps me to identify the test case. My code look like this

final String CLASS_NAME = new Object() {
  }.getClass().getName();

@Test
  public void bigNumTest() {

    final String METHOD_NAME = new Object() {
    }.getClass().getEnclosingMethod().getName();
    String testName = CLASS_NAME + "/" + METHOD_NAME + "\n the input is";

    long bigNumber = 123456789l;
    assertEquals(testName+bigNumber, CollatzConjectureLength.main(bigNumber), conjecture(bigNumber));
 }

However, it's look busy so I wanna hide the automation. e.g.

@Test
 public void bigNumTest(){
  long bigNumber = 123456789l;
 assertEqualsWithId(CollatzConjectureLength.main(bigNumber),conjecture(bigNumber))
}

However, I cannot call

 final String METHOD_NAME = new Object() {
        }.getClass().getEnclosingMethod().getName();

from the other method

the other solution is from stackOverflow

public static String getMethodName(final int depth)
{
  final StackTraceElement[] ste = Thread.currentThread().getStackTrace();

  //System. out.println(ste[ste.length-depth].getClassName()+"#"+ste[ste.length-depth].getMethodName());
  // return ste[ste.length - depth].getMethodName();  //Wrong, fails for depth = 0
  return ste[ste.length - 1 - depth].getMethodName(); //Thank you Tom Tresansky
}

This solution may got the wrong method name due to the deep of method call?

Is there any better solution?

Upvotes: 0

Views: 93

Answers (1)

Mathias Begert
Mathias Begert

Reputation: 2471

If you are using JUnit 4.7 or above you could try this:

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

copied from here: https://github.com/junit-team/junit/wiki/Rules#testname-rule

Upvotes: 4

Related Questions