2013-12-16 110 views
1

我正在使用TestNG進行單元測試。我正在使用@BeforeMethod保存記錄,然後執行更新,搜索,刪除測試。TestNG:如何跳過@BeforeMethod調用一些測試

我正在尋找可以避免執行某些測試用例的方法調用的方法@BeforeMethod。例如,我有三個測試保存,更新和刪除。在這種情況下,我只想致電@BeforeMethod進行更新,並刪除測試而不進行保存測試。任何想法?

請注意,我不想使用@DependesOnMethods,因爲它不被推薦。

在此先感謝。

我的測試類看起來象下面這樣:

@ContextConfiguration("file:application-context-test.xml") 
@TransactionConfiguration(transactionManager = "transactionManager", defaultRollback = true) 
public class MyEntityTest { 

    int long myEntityId; 

    @BeforeMethod 
    public saveRecord(){ 
     session=getCurrentSessionFactory() 
     myEntity = new myEntity(); 
     myEntityId = session.save(myEntity) 
    } 

    @Test 
    public saveTest(){ 
     session=getCurrentSession() 
     myEntity =session.getByID(myEntityId) 
     session.save(myEntity) 
    } 

    @Test 
    public updateTest(){ 
     session=getCurrentSession() 
     myEntity =session.getByID(myEntityId) 
     session.update(myEntity) 
    } 
} 

回答

1

,你可以在測試中它會調用一個單獨的beforeMethod針對不同的組羣 http://testng.org/doc/documentation-main.html#test-groups

+0

按詳細描述這個頁面http://testng.org/javadoc/org/testng/annotations/BeforeMethod.html「對於方法之前(beforeSuite ,beforeTest,beforeTestClass和beforeTestMethod,但不是beforeGroups):如果alwaysRun設置爲true,則將運行此配置方法,而不管它屬於哪個組。這意味着@BeforeMethod屬於一個組,即使該組未被調用測試,該組也將始終被調用。 –

+0

如果你正在使用alwaysRun,你迫使它執行。通過在您的測試方法中調用標註爲@beforeMethod的方法來重構簡單代碼。 – geddamsatish

+0

如果@beforeMethod使用簡單,我如何給這個方法的組名稱。另外,alwaysRun默認爲true。它將始終執行,即使它不屬於組 –

1

TestNG的支持一些參數的本地注射,例如有關要調用的方法的信息。所以,你可以用下面的辦法:

import java.lang.reflect.Method; 
... 
@BeforeMethod 
public saveRecord(Method method){ 
    if (!method.getName().equals("saveTest")) { 
    session=getCurrentSessionFactory() 
    myEntity = new myEntity(); 
    myEntityId = session.save(myEntity) 
    } 
} 

http://testng.org/doc/documentation-main.html#native-dependency-injection