2012-09-18 112 views
7

我有一个方面在从我的TestNG测试方法抛出异常后运行。我想将Test方法名称放入我的aspectj方法中。如何获取在Java中抛出异常的方法名称

对这个有什么想法?请在下面找到我的代码示例:

看点:

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

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

测试:

@Test 

public void testScenarioOne(){ 
    logger.debug("From Scenario One Test"); 
    Assert.assertEquals(true, false); 
} 

回答

4

您需要将您的切入点类型更改从callexecution

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

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

编辑:也许这将是更清洁,专门拦截@Test注解的方法:

import org.testng.annotations; 

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

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

谢谢!将切入点类型从调用更改为执行的技巧。 (第二个片段没有被编译)。 – rookie007r

+0

据我所知,我只是从编辑器中复制并粘贴了第二个代码,它编译得很好。你可以说得更详细点吗?你会得到哪个错误信息? – kriegaex

+0

您得到的错误可能是因为您需要指定完全限定的软件包,例如pointcut testMethod():execution(@ org.testng.annotations.Test * *(..)); –

2

您可以使用:

thisJoinPoint.getSignature().getName() 

虽然你将不得不直接从抛出异常你的测试方法。 Assert.equals()抛出的异常不是你的测试方法。

+1

我觉得thisStaticJoinPoint会也工作。 –

+1

恩......谢谢!但是这给了我“assertEquels”方法。我需要测试方法(即testScenarioOne)。 – rookie007r