2017-05-29 27 views
0

我想在運行時根據一些條件如何使用TestNG動態地將測試組設置爲@Test方法?

假設我下面的類

public class MyTest1{ 
    @Test 
    public void test1(){ 
    System.out.println("test1 called"); 
    } 
} 

public class MyTest2{ 
    @Test(groups={"group1"}) 
    public void test2(){ 
    System.out.println("test2 called"); 
    } 

    @Test(groups={"group2"}) 
    public void test3(){ 
    System.out.println("test3 called"); 
    } 
} 

現在運行測試時我送「-groups組1」或設置組特定@Test方法「 -groups group2「在命令行中輸入TestNG。因此,根據傳遞的組名,testng運行test2()或test3()。現在我的要求是運行test1(),它不應該附加任何組。無論我爲testng runner提供哪個組,test1()都應該每次運行。我嘗試着實現IAlterSuiteListener的alter方法,但是我無法獲得所有的測試方法,包括哪些不被考慮運行。所以我無法在運行時設置組名。

那麼有沒有其他方法可以在運行時將組設置爲@Test方法(沒有定義組)?

回答

1

你或許應該開始探索方法選擇的是TestNG的提供給您用於此目的的BeanShell的方式。

有時候,我寫了一篇博文,談論如何在TestNG中使用Beanshell表達式。您可以閱讀更多關於它的文章here並參考官方的TestNG文檔here

引述TestNG的文檔,

TestNG的定義以下變量爲了您的方便:

  • java.lang.reflect.Method中的方法:目前的測試方法。
  • org.testng.ITestNGMethod testng方法:當前的測試方法。
  • java.util.Map組:當前測試方法所屬組的映射。

所以只用你的榜樣,我繼續創建一套XML文件看起來像下面

<?xml version="1.0" encoding="UTF-8"?> 
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd"> 
<suite name="1265_Suite" parallel="false" verbose="2"> 
    <test name="92" parallel="false" preserve-order="true"> 
     <method-selectors> 
      <method-selector> 
       <script language="beanshell"> 
        <![CDATA[whatGroup = System.getProperty("groupToRun"); 
       (groups.containsKey(whatGroup) || testngMethod.getGroups().length ==0); 
       ]]> 
       </script> 
      </method-selector> 
     </method-selectors> 
     <classes> 
      <class name="com.rationaleemotions.stackoverflow.MyTest1"/> 
      <class name="com.rationaleemotions.stackoverflow.MyTest2"/> 
     </classes> 
    </test> 
</suite> 

我用如下的Maven通過命令提示符下運行:(測試類基本上是你在你的問題分享)

mvn clean test -DsuiteXmlFile=dynamic_groups.xml -DgroupToRun=group2 

------------------------------------------------------- 
T E S T S 
------------------------------------------------------- 
Running TestSuite 
... 
... TestNG 6.11 by Cédric Beust ([email protected]) 
... 

test1 called 
test3 called 
Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 15.377 sec - in TestSuite 

Results : 

Tests run: 2, Failures: 0, Errors: 0, Skipped: 0 
+0

我在這裏有一個問題。如果我提供-DgroupToRun = group1,group2,它會起作用嗎? –

+0

你是什麼意思,它不適合你?你能幫忙詳細說明什麼不適合你嗎? –

+0

而且,如果您嘗試指定多個組,因爲我在我的答案中共享的beanshell只處理1組,所以它不會工作。您需要增強它以支持多個組。 –

0

如果您指定組,則沒有直接的方法來做到這一點。但是,還有其他兩種方法可以做到這一點。

  1. 您可以標記有一個名爲「nogroups」和組中沒有組所有的測試包括組,而您運行 或者
  2. 如果你有,你已經測試龐大的數字,然後寫了一個註釋變壓器基本上增加了這個組中沒有組的情況 - 下面的例子。編寫變壓器可以幫助您以編程方式控制邊界情況。

public void transform(ITestAnnotation annotation, Class testClass, Constructor testConstructor, Method testMethod) { if (annotation.getGroups().length == 0) { annotation.setGroups(new String[]{"noGroups"}); } }

+0

在這種情況下,我將不得不指定noGroups testng亞軍。然後出現同樣的問題。我可以用測試方法本身而不是使用變壓器來附加noGroups。 –

+0

這是我給你的第一個選擇。無論哪種情況,您都需要在xml或runner中指定noGroups –

相關問題