2012-09-18 385 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