2016-08-04 31 views
1

我想下面的代碼:dependsOnMethods爲@AfterTest沒有找到測試方法

public class ShashiTest { 
    @Test 
    public void test1(){ 
     System.out.println("1==========="); 
    } 

    @Test(dependsOnMethods="test1") 
    public void test2(){ 
     System.out.println("2==========="); 
    } 

    @Test(dependsOnMethods="test2") 
    public void test3(){ 
     System.out.println("3==========="); 
    } 

    @AfterMethod(dependsOnMethods={"test2","test3"}) 
    public void test4(){ 
     System.out.println("4==========="); 
    } 
} 

我期待輸出:

1=========== 
2=========== 
4=========== 
3=========== 
4=========== 

但我得到異常的測試方法未找到:

com.ShashiTest.test4() is depending on method public void com.ShashiTest.test2(), which is not annotated with @Test or not included. 
    at org.testng.internal.MethodHelper.findDependedUponMethods(MethodHelper.java:111) 

我在哪裏犯錯誤?我如何實現我的目標?

+0

請參閱下面的Julien Herr的回答。一個快速的觀察:一旦你開始取決於多種方法,我建議依賴於組,而這更容易維護。但你絕對看起來在這裏找到了一個bug。 –

回答

2

@AfterMethod聲明在每個使用@Test註解的方法後運行此方法。現在你和test4()在test1()和test2()之前被調用,同時也要求它在test2()之後運行。請參閱this進行更深入的討論。

編輯:我應該可能使呼叫順序更清晰。

test1()->test4() 
test2()->test4() 
test3()->test4() 

正如你所看到的,需要TEST4()將TEST2後運行()和TEST3()與要求每一個方法後,被稱爲@AfterMethod批註衝突。

+0

哦!可能我需要更詳細地通過這些屬性。 @JohnK基本上我不想寫兩次test4()方法,我想在test2()和test3()之後運行test4(),但不是在test1()之後運行。任何想法我怎麼能得到這個? –

+0

對於這樣的事情,我認爲最好的答案是讓test2和test3手動調用test4作爲方法的最後一行。 @ nick-humrich對測試設置和撕裂有很好的解釋[這裏](http://stackoverflow.com/a/20642025/5273975) –

+0

單元測試依賴執行順序通常是一種糟糕的做法。所有的單元測試必須是獨立的。 http://stackoverflow.com/questions/3693626/how-to-run-test-methods-in-specific-order-in-junit4 –

1

dependsOnMethod不能像那樣工作,只是用來爲它們之間的方法排序。 的javadoc是足夠清晰IMO:

The list of methods this method depends on. There is no guarantee on the order on which the methods depended upon will be run, but you are guaranteed that all these methods will be run before the test method that contains this annotation is run. Furthermore, if any of these methods was not a SUCCESS, this test method will not be run and will be flagged as a SKIP. If some of these methods have been overloaded, all the overloaded versions will be run.

但例外是不應該的,所以我爲它打開an issue

關於您的需求,其運行的具體使用方法的@AfterMethod只(東西看起來奇怪,但爲什麼不),你可以做到以下幾點:

public class ShashiTest { 
    @Test 
    public void test1(){ 
     System.out.println("1==========="); 
    } 

    @Test(dependsOnMethods="test1") 
    public void test2(){ 
     System.out.println("2==========="); 
    } 

    @Test(dependsOnMethods="test2") 
    public void test3(){ 
     System.out.println("3==========="); 
    } 

    @AfterMethod 
    public void test4(Method m){ 
     switch(m.getName()) { 
      case "test2": 
      case "test3": 
       System.out.println("4===========");  
     } 
    } 
} 

應該按預期工作。

0

有點晚回答,但我今天剛剛面對這個問題。錯誤:com.expedia.FlightBooking.tearDown()取決於方法public void com.expedia.FlightBooking.flightBooking(),它不用@Test註釋或不包含。

解決方案:將dependsOnMethods更改爲dependsOnGroups例如:@AfterTest(dependsOnGroups = {「flightBooking」})已解決我的問題。