Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

junit, get the failed method name

Tags:

java

junit

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.

like image 443
nzsquall Avatar asked Nov 26 '25 22:11

nzsquall


1 Answers

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());
like image 73
Sotirios Delimanolis Avatar answered Nov 28 '25 12:11

Sotirios Delimanolis



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!