nzsquall
nzsquall

Reputation: 405

junit, get the failed method name

I am using Junit and I want to log the test method name and maybe some stack trace when the test fails, is there a way to do that?

I have my example code below:

public class TestGoogleHomePage extends Browser {

@Test
public void testLoadGoogle() {
       ...............
       //assume this case will fail
}

@Test
public void testSearchGoogle() {
       .......
}

  @Rule
public TestWatcher watchman = new TestWatcher() {

    @Override
    protected void failed(Throwable e, Description description) {
        System.out.println("test fail");
        System.out.println(Thread.currentThread().getStackTrace()[1]
                .getMethodName());
    }

    @Override
    protected void succeeded(Description description) {
    ......

    }
};

}

The statement System.out.println(Thread.currentThread().getStackTrace()[1] .getMethodName()); will print method failed, instead of testLoadGoogle. Is there a way I can capture the name of the failed method instead?

Can I also print the stack trace as well?

Also if I can avoid adding extra codes in the actual test for this purpose, it will be great. Because I don't want to repeat that codes for every of my test case.

Thanks advance for your help.

Upvotes: 4

Views: 1199

Answers (1)

Sotirios Delimanolis
Sotirios Delimanolis

Reputation: 279930

The Description class has a getMethodName() method that states

Returns

If this describes a method invocation, the name of the method (or null if not)

So just call it

System.out.println(description.getMethodName());

Upvotes: 1

Related Questions