Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the method name that thrown the exception in Java

Tags:

java

aop

aspectj

I have an aspect that runs after an exception is thrown from my TestNG test method. I would like to get the Test method name into my aspectj method.

Any thoughts on this? Please find my code sample below:

Aspect:

pointcut publicCall(): call(public * *(..));

after() throwing (AssertionError e): publicCall() {
    logger.debug("Assertion Error thrown");
    System.out.println("Threw an exception: " + e);
}

Test:

@Test

public void testScenarioOne(){
    logger.debug("From Scenario One Test");
    Assert.assertEquals(true, false);
}
like image 295
rookie007r Avatar asked Sep 18 '12 21:09

rookie007r


2 Answers

You need to change your pointcut type from call to execution:

pointcut publicMethod(): execution(public * *(..));

after() throwing (AssertionError e): publicMethod() {
    System.out.println(thisJoinPointStaticPart.getSignature());
}

Edit: Maybe it would be even cleaner to specifically intercept @Test annotated methods:

import org.testng.annotations;

public aspect TestExceptionInterceptor {
    pointcut testMethod(): execution(@Test * *(..));

    after() throwing (AssertionError e): testMethod() {
        System.out.println(thisJoinPointStaticPart.getSignature());
    }
}
like image 152
kriegaex Avatar answered Dec 29 '22 01:12

kriegaex


You can use:

thisJoinPoint.getSignature().getName()

although you will have to throw the exception directly from your test method. Assert.equals() is throwing the exception not your test method.

like image 24
Reimeus Avatar answered Dec 28 '22 23:12

Reimeus